NSArray writeToFile fails

前端 未结 2 1653
北恋
北恋 2020-12-13 20:14

I am trying to save an array, which has some dictionaries inside, to a plist file but it fails. I don\'t get any errors. I do exactly the same few lines above in the code ju

相关标签:
2条回答
  • 2020-12-13 20:51

    If you read the documentation closely, writeToFile:atomically: expects the array to contain only objects which can be written into a plist file.

    Only objects of type:

    • NSString
    • NSData
    • NSDate
    • NSNumber
    • NSArray
    • NSDictionary

    are permitted. If you have arrays or dictionaries within the array you're saving, their values will be examined by the same criteria.

    This is somewhat more restrictive than what's usually allowed in NSArrays. In particular, the value [NSNull null] is not acceptable.

    0 讨论(0)
  • 2020-12-13 20:52

    I convert NSArray or NSDictionary to NSData before serializing. Following is a category on nsarray for serializing and deserializing. This comfortableby handles some data being nsnull

    @implementation NSArray(Plist)
    
    -(BOOL)writeToPlistFile:(NSString*)filename{
        NSData * data = [NSKeyedArchiver archivedDataWithRootObject:self];
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
        BOOL didWriteSuccessfull = [data writeToFile:path atomically:YES];
        return didWriteSuccessfull;
    }
    
    +(NSArray*)readFromPlistFile:(NSString*)filename{
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
        NSData * data = [NSData dataWithContentsOfFile:path];
        return  [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    
    @end //needs to be set for implementation
    
    0 讨论(0)
提交回复
热议问题