Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writeToFile not working with NSDictionary [duplicate]

I looked around other similar questions about this but nothing really worked.

I managed to write only one pair (object / key) of the dictionary (e.g.: setObject:itemProperties[0] forKey[0]) on my Plist. But I would like all the objets and keys to be added. I didn't managed so far (return the error). Any help?

 // Path to Documents Folder

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"items.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"items.plist"] ];
}

NSMutableDictionary *items;

if ([fileManager fileExistsAtPath: path])
{
    items = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
}
else
{
    // If the file doesn’t exist, create an empty dictionary
    items = [[NSMutableDictionary alloc] initWithCapacity:5];
}

// array of the item properties
NSArray *itemProperties = @[myItem.itemTitle, myItem.itemImage, myItem.itemPositionX, myItem.itemPositionY, myItem.itemHeight, myItem.itemWidth];

// Set the key values for each field    
NSArray *keys = @[@"Title", @"Image", @"PositionX", @"PositionY", @"Height", @"Width"];


[items setObject:itemProperties forKey:keys];

//Save dictionnary to Plist
[items writeToFile: path atomically:YES];

if (![items writeToFile:path atomically:YES]) {
    NSLog(@"Error with creating Plist");
}
like image 986
Xavier Avatar asked Nov 27 '22 21:11

Xavier


1 Answers

You can not control the content you are going to write sometimes. For example, you can't avoid a null value when you are going to write a JSON object that is gotten from a server.

NSData is compatible with these "invalid" values, so converting NSArray or NSDictionary to NSData is an ideal way in these cases.

write:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject];
[data writeToFile:path atomically:YES];

read:

NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
like image 171
Brian Avatar answered Dec 25 '22 09:12

Brian