IPHONE: saving and extracting a dictionary of dictionaries from plist

I have a main dictionary where each entry is a dictionary. I need to save this on a plist and then get its contents.

This is what I do to save the dictionary

// create a dictionary to store a fruit characteristics
NSMutableDictionary *fruit = [[NSMutableDictionary alloc] init];
[fruit setObject:quantity forKey:@"quantity"];
[fruit setObject:productID forKey:@"productID"];
[fruit setObject:nameID forKey:@"nameID"];

// create a dictionary to store all fruits
NSMutableDictionary *stock = [[NSMutableDictionary alloc] init];
[stock setObject:fruit forKey:@"nameID"];

... after adding all the fruits to the stock dictionary, write the stock on plist

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

NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path];
[stock writeToFile:path atomically:YES];

... to restore the dictionary, I use

NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path];

... but it doesn’t save anything in the file ... what am I missing?

Thanks for any help.

+3
source share
3 answers

You write:

... after adding all the fruits to the exchange dictionary, write PLIST

, . , , .plist, , writeToFilePath .

:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"stock.plist"];
// write plist to disk
[stock writeToFile:path atomically:YES];

// read it back in with different dictionary variable
NSMutableDictionary *savedStock = [NSMutableDictionary dictionaryWithContentsOfFile:path];
if( savedStock==nil ){
    NSLog(@"failed to retrieve dictionary from disk");
}

, productID? - , , , :

[fruit setObject:[NSNumber numberWithInt:quantity] forKey:@"quantity"];

, .

+10

dictionaryWithContentsOfFile , . , .

- :

[stock writeToFile:path atomically:YES];
+5

() stock . , nil. , . stock, .

(, , , NSMutableDictionary *stock writeToFile.)

(, , .)

+1

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


All Articles