Why NSMutableDictionary don't want write to file?

前端 未结 2 1856
遥遥无期
遥遥无期 2020-12-18 09:59
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[NSFileManager defaultManager] fileExistsAtPath:pathString]) 
    {
        infoDict = [[NSMutableDictionary          


        
相关标签:
2条回答
  • 2020-12-18 10:10

    writeToFile:atomically only works if the dictionary you call it on is a valid property list object (see docs).

    For a NSDictionary to be a valid property list object, among other things, its keys must be strings, but in your example the keys are NSNumber instances.

    0 讨论(0)
  • 2020-12-18 10:24

    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];
    
    0 讨论(0)
提交回复
热议问题