I am trying to write data into my plist
file, which was created in Library/Caches
in my app's sandbox, with the following custom helper method:
-(void)saveStatusesToPlist:(NSArray *)array
{
NSDictionary *dict = @{@"data": array};
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString *plistPath = [cachesDirectory stringByAppendingPathComponent:filepath];
NSLog(@"PATH: %@", plistPath);
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:plistPath]) {
BOOL isCreated = [manager createFileAtPath:plistPath contents:nil attributes:nil];
NSLog(@"Result:%@", isCreated? @"Success": @"Failed");
}
BOOL flag = [dict writeToFile:plistPath atomically:YES];
NSLog(@"Write result:%@", flag? @"Success": @"Failed");
}
Please notice that the parameter: array
is an array of many NSDictionary
objects converted from JSON
data which was fetched from server side over network.
UPDATE: I got my array like this:
NSArray *array = [result objectForKey:@"array"];
But the result was always failed.
So I doubted that issue was from the array
which may contain invalid data. Then I tried hardcode the array
to sth like @[@"key1": @"value1", @"key2": @"value2", @"key3": @"value3"]
.
With the hardcoded data, the flag
returns YES
meaning it was saved.
So at least I can tell that my fetched data has some problem but I don't know where it is.
Seems like issue is in Dictionary's size… I created array with 30 dictionaries with 40 items on each. And I can't write it… BUT!!! ;) You can make something like this:
NSData* data = [NSKeyedArchiver archivedDataWithRootObject:dict];
BOOL flag = [data writeToFile:plistPath atomically:YES];
NSData* savedData = [NSData dataWithContentsOfFile:plistPath];
NSDictionary* unarchivedDict = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:savedData];
In this case - everything works fine.