Converting NSNumbers saved in a plist to integers - ios

Saving data:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *number = [NSNumber numberWithInt:points];
[array addObject:number];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
Reading data:
BestLabel.text will display the high score. I get a warning: "assignment makes integer from pointer without a cast"
-(void)LoadData{
BestLabel.center = CGPointMake(150,300);
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
loadint = [array objectAtIndex:0];
NSString *myString35 = [NSString stringWithFormat:#"%d", loadint];
BestLabel.text = myString35;
[array release];
}
}
The sample code I got this from was saving and loading text fields with no problem.. I suppose I could do a string to int conversion, but that seems unnecessary. Thanks for your help!
EDIT:
- (void)applicationWillTerminate:(NSNotification *)notification
{
NSMutableArray *array = [[NSMutableArray alloc] init];
if (points > highscore){
NSString *myString35 = [NSString stringWithFormat:#"%d", points];
[array addObject:myString35];
}else {
NSString *myString35 = [NSString stringWithFormat:#"%d", highscore];
[array addObject:myString35];
}
NSNumber *number = [NSNumber numberWithInt:GreenBlot.center.x];
[array addObject:number];
NSNumber *number2 = [NSNumber numberWithInt:GreenBlot.center.y];
[array addObject:number2];
And now loading with:
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
BestLabel.text = [array objectAtIndex:0];
highscore = [[array objectAtIndex:0] intValue];
lx = [[array objectAtIndex:1] intValue];
ly = [[array objectAtIndex:2] intValue];
GreenBlot.center = CGPointMake( lx,ly);
[array release];
}
lx and ly are integers. I tried CGPointMake( [[array objectAtIndex:1] intValue], [[array objectAtIndex:2] intValue] ) first. Same results, GreenBlot is getting centered at 0,0. Any idea why?

The easiest thing to do is use NSNumber's intValue method:
loadint = [[array objectAtIndex:0] intValue];

You need the second line below:
loadint = [array objectAtIndex:0];
int score = [loadint intValue];
NSString *myString35 = [NSString stringWithFormat:#"%d", loadint];
If you are only saving one value, then use a NSDictionary with a key that makes it easier for you to label the value you are saving.

CGPointMake is defined:
CGPoint CGPointMake(
float x,
float y
)
You are taking GreenBlot.center.x which is presumably a float and feeding it to NSNumber as an int.... Go back and look at the types of your variables and change to [NSNumber numberWithFloat:...] and lx = [[array objectAtIndex:1] floatValue]; etc., as appropriate.
Also, you've created a different question in your editing of the original question.

Related

Read csv file ios

i have a problem for read a csv file. Only the last line of csv file is display.
However in my fetchedResultsController i have 2 lines
This is the code :
NSString * writeString;
NSInteger i = 0;
for (id object in [[self fetchedResultsController] fetchedObjects]) {
NSString * object1 = [[object valueForKey:#"object1"] description];
NSString * object2 = [[object valueForKey:#"object2"] description];
NSString * object3 = [[object valueForKey:#"object3"] description];
NSString * object4 = [[object valueForKey:#"object4"] description];
writeString = [NSString stringWithFormat:#"%#, %#, %#, %#, \n", object1, object2, object3, object4];
i++;
NSLog(#"%# - %i", writeString, i);
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* savePath = [paths objectAtIndex:0];
savePath = [savePath stringByAppendingPathComponent:#"myfile.csv"];
[writeString writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#", savePath);
NSString *fullPath = savePath;
[self readTitleFromCSV:fullPath AtColumn:0];
And The readTitleFromCSV method :
-(void)readTitleFromCSV:(NSString*)path AtColumn:(int)column
{
NSMutableArray *titleArray=[[NSMutableArray alloc]init];
NSString *fileDataString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *linesArray=[fileDataString componentsSeparatedByString:#"\n"];
int k=0;
for (id string in linesArray)
if(k<[linesArray count]-1){
NSString *lineString=[linesArray objectAtIndex:k];
NSArray *columnArray=[lineString componentsSeparatedByString:#","];
[titleArray addObject:[columnArray objectAtIndex:column]];
k++;
}
NSLog(#"%#",titleArray);
}
Thank you for your help.
Try to use NSMutableString instead of NSString:
NSMutableString *writeString = [NSMutableString string];
And then in the for loop:
[writeString appendString:[NSString stringWithFormat:#"%#, %#, %#, %#, \n", object1, object2, object3, object4]];

Trying to read integers from plist results in unexpected results

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"levels.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"levels" ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *levels = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSMutableArray *playLevel = (NSMutableArray *)[levels objectForKey: #"0"];
// Initialize the correct grid for answer checking.
correctGrid = [[NSMutableArray alloc] init];
for (int row = 0; row < 5; row++) {
NSMutableArray* subArr = [[NSMutableArray alloc] init];
for (int col = 0; col < 5; col++) {
int index = row * 5 + col;
int number = [playLevel objectAtIndex:index];
NSNumber *item = [NSNumber numberWithInt: number];
[subArr addObject:item];
}
[correctGrid addObject: subArr];
}
I'm new to objective-c and I'm trying to read integer values from a plist that is structured as a dictionary of arrays. Using the breakpoint/debugger in xcode shows that the plist is being successfully read. However when I try to retrieve the number from the array playLevel, each number is some ridiculously high integer such as 164911184, when the array is just all zeros. Does this have something to do with pointers? Help appreciated.
A plist can't store integers, it stores NSNumbers. So, most likely, you can change these two lines,
int number = [playLevel objectAtIndex:index];
NSNumber *item = [NSNumber numberWithInt: number];
to,
NSNumber *item = [playLevel objectAtIndex:index];

Need help in trying to read and write from plist

I am trying to save an NSMutable Array and NSString into plist and then if it exists initialize the value from plist. However when I re run the app, the values do not get initialize as it is suppose to. So far the following is what I have.
if (self = [super init]) {
NSString *path=[self getFileUrl];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
_history = [d objectForKey:#"stringKey"];
class=[d objectForKey: #"ArrayKey"];
}
NSDictionary *d;
However the values are not getting initialized as per the plist. Is it the way I am extracting the values from the dictionary?
here is my function that saving json into plist in nscachesdirectory
-(void)saveproducts{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSDictionary*dict = [NSDictionary dictionary];
NSMutableArray *types = [NSMutableArray array];
NSArray *dictArray = [NSArray array];
NSArray *dictKeys = [NSArray array];
NSArray *productObjects = [NSArray array];
NSArray *productKeys = [NSArray array];
for (int i=0; i<appDelegate.products.count; i++) {
NSMutableArray *tmpProds = [NSMutableArray array];
NSString *t_ID = [[appDelegate.products objectAtIndex:i] valueForKey:#"id"];
NSString *t_image = [[appDelegate.products objectAtIndex:i] valueForKey:#"image"];
NSString *t_name =[[appDelegate.products objectAtIndex:i] valueForKey:#"name"];
NSArray *products = [[appDelegate.products objectAtIndex:i] valueForKey:#"products"];
NSDictionary *productsDict = [NSDictionary dictionary];
for (int j=0; j<products.count; j++) {
NSString *p_id = [[products objectAtIndex:j] valueForKey:#"id"];
NSString *p_name = [[products objectAtIndex:j] valueForKey:#"name"];
NSString *p_name2 = [[products objectAtIndex:j] valueForKey:#"name2"];
NSString *image = [[products objectAtIndex:j] valueForKey:#"image"];
NSString *typeID = [[products objectAtIndex:j] valueForKey:#"type_id"];
NSString *active = [[products objectAtIndex:j] valueForKey:#"active"];
NSString *available = [[products objectAtIndex:j] valueForKey:#"available"];
NSString *desc = [[products objectAtIndex:j] valueForKey:#"description"];
NSString *price = [[products objectAtIndex:j] valueForKey:#"price"];
if ([p_name2 isEqual:[NSNull null]]) {
p_name2 =#"undefined";
}
if ([desc isEqual:[NSNull null]]) {
desc = #"";
}
productObjects = [NSArray arrayWithObjects:p_id,p_name,p_name2,image,typeID,active,available,desc,price, nil];
productKeys = [NSArray arrayWithObjects:#"id",#"name",#"name2",#"image",#"type_id",#"active",#"available",#"desc",#"price", nil];
productsDict = [NSDictionary dictionaryWithObjects:productObjects forKeys:productKeys];
[tmpProds addObject:productsDict];
if (![image isEqualToString:#""]) {
[foodImages addObject:image];
}
}
dictArray = [NSArray arrayWithObjects:t_ID,t_image,t_name,tmpProds, nil];
dictKeys = [NSArray arrayWithObjects:#"id",#"image",#"name",#"products", nil];
dict = [NSDictionary dictionaryWithObjects:dictArray forKeys:dictKeys];
[types addObject:dict];
}
NSDictionary* plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:types, nil] forKeys:[NSArray arrayWithObjects:#"ptype", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"cached"];
[defaults synchronize];
}
else
{
NSLog(#"Error log: %#", error);
}
}
and this one reading plist
-(void)loadFromplist{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *dict = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
productsArray = [dict valueForKey:#"ptype"];
[self.tableView reloadData];
}

how to store NSMutableArray in plist [duplicate]

This question already has answers here:
How to Save NSMutableArray into plist in iphone
(4 answers)
Closed 9 years ago.
I have NSMutableArray with name "add" that has in self name of cell (in UITableView)
I want store this "add" NSMutableArray in .plist file.
this is "add" code:
//NSArray *NaMe;
//NSMutableArray *add;
//NSMutableArray *all;
for (int i =0; i<11; i++) {
NSIndexPath *indexPath = [self.Table indexPathForSelectedRow];
NaMe = [[all objectAtIndex:(indexPath.row)+i]objectForKey:#"name"];
if(!add){
add = [NSMutableArray array];
}
[add addObject:NaMe];
}
NSLog(#"%#",add);
this add show me name of cell and I want store this name in .plist file.
I assume you want to save the plist for persistence.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Names.plist"];
[add writeToFile:filePath atomically:YES];
To read back from plist
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpathsobjectAtIndex:0];
NSString*pListpath = [pListdocumentsDirectory stringByAppendingPathComponent:#"Apps.plist"]; NSFileManager*pListfileMgr = [NSFileManager defaultManager];
//Create a plist if it doesn't alread exist
if (![pListfileMgrfileExistsAtPath: pListpath])
{
NSString*bundle = [[NSBundle mainBundle]pathForResource:#"Apps" ofType:#"plist"];
[pListfileMgrcopyItemAtPath:bundletoPath: pListpatherror:&error];
}
//Write to the plist
NSMutableDictionary*thePList = [[NSMutableDictionary alloc] initWithContentsOfFile: pListpath];
[thePList setObject:[NSString stringWithFormat:#"YourContent"] forKey:#"Related Key"];
[thePList writeToFile: pListpathatomically: YES];
Try This Sample Code
The solution is quite simple.
Create an NSArray containing your NSMutableArray, then write it to a path.
NSArray *yourArray=[NSArray arrayWithObjects:<#(id), ...#>, nil];
NSArray *yourPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libDir = [yourPath objectAtIndex:0];
NSString *loc = [libDir stringByAppendingString:#"/anyfilename.plist"];
[yourArray writeToFile:loc atomically:YES];
Fetch your array using:
yourPath = [bundle pathForResource:#"anyfilename" ofType:#"plist"];
yourArray = (yourArray!= nil ? [NSArray arrayWithContentsOfFile:loc] : nil);
user this code
#define DOC_DIR [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSArray *NaMe;
NSMutableArray *add;
NSMutableArray *all;
for (int i =0; i<11; i++) {
NSIndexPath *indexPath = [self.Table indexPathForSelectedRow];
NaMe = [[all objectAtIndex:(indexPath.row)+i]objectForKey:#"name"];
if(!add){
add = [NSMutableArray array];
}
[add addObject:NaMe];
}
NSLog(#"%#",add);
[self writeDataToPlistFromArray:add];
-(void) writeDataToPlistFromArray:(NSArray *) dataArray
{
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:dataArray,#"Root", nil];
NSString *path = [DOC_DIR stringByAppendingPathComponent:#"Names.plist"];
[dic writeToFile:path atomically:YES];
}

Deleting in NSMutableArray

I have an array here, example I have 4 images on each column, each responds to its default index:
When an image is deleted for example index 1. as shown in the image below:
The index becomes 0,1,2 :
which I want to be is 0,2,3 (Which is the original array index):
Could anyone help me on how to achieve this?
my code for my array:
self.myImages = [NSMutableArray array];
for(int i = 0; i <= 10; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"myImages%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[images addObject:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
You can put another key in your dictionary which will correspond to the index before any removal of objects. Display it instead of the index and you will get the desired result.
edit 2:
self.myImages = [NSMutableArray array];
for(int i = 0; i <= 10; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"myImages%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"image"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index"];
[images addObject:container];
[container release]; // if not using ARC
}
}
And when you're getting the corresponding object, you do:
NSDictionary *obj = [images objectAtIndex:someIndex];
UIImage *objImg = [obj objectForKey:#"image"];
int objIndex = [[obj objectForKey:#"index"] intValue];
use an NSMutableDictionary instead
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:#"Item 0" forKey:#"0"];
[dictionary setValue:#"Item 1" forKey:#"1"];
[dictionary setValue:#"Item 2" forKey:#"2"];
[dictionary setValue:#"Item 3" forKey:#"3"];
// 0 = "Item 0";
// 1 = "Item 1";
// 2 = "Item 2";
// 3 = "Item 3";
NSLog(#"%#", dictionary);
//Remove the item 1
[dictionary removeObjectForKey:#"1"];
// 0 = "Item 0";
// 2 = "Item 2";
// 3 = "Item 3";
NSLog(#"%#", dictionary);

Resources