WriteToFile does not work with NSDictionary

I looked at other similar questions, but nothing really worked.

I managed to write only one pair (object / key) of the dictionary (for example: setObject: itemProperties [0] forKey [0]) on my Plist. But I would like all objects and keys to be added. Until I managed (returned an 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"); } 
+4
source share
2 answers

Are you using the correct keys and values ​​correctly?

This method recursively checks that all contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray or NSDictionary) before writing to the file and returns NO if all objects are not objects of the property list, since the resulting file will not be a valid property list .

Link: writeToFile: atomically:

+8
source

You cannot control the content that you intend to write sometimes. For example, you cannot escape the null value when you are going to write a JSON object received from the server.

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

records:

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

in the following way:

 NSData *data = [NSData dataWithContentsOfFile:path]; NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
+17
source

Source: https://habr.com/ru/post/1500875/


All Articles