Problem with writeToFile with array of NSDictionary objects
I'm trying to write an array of NSDictionary objects to a .plist file on the iPhone (OS 3.0). (They are actually NSCFDictionary objects whe开发者_JAVA技巧n I call the [object class] method). My problem is that it won't write to file. If I set the array to "nil" it at least creates the empty plist file but won't do it if I have these objects in the array.
My array is a parsed response from a JSON HTTP request and looks like this:
{
"title" = "A Movie";
"time_length" = "3:22";
},
{
"title" = "Another Movie";
"time_length" = "1:40";
},
{
"title" = "A Third Movie";
"time_length" = "2:10";
}
The code to create the file is:
[array writeToFile:[self dataFilePath] atomically:YES];
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}
Could the NCSFDictionary class of the objects in my array be preventing me from writing to file? Thanks for your help.
-writeToFile should work, assuming EVERY object, no matter how 'deep' in your original array, is either an NSNumber, an NSString, an NSDate, an NSBoolean, an NSDictionary, or an NSArray. If there's any other sort of object in there, it will fail.
Try using the code below to get the document directory instead:
NSString * documentsDirectory = [@"~/Documents/" stringByExpandingTildeInPath];
What you're doing should be fine, but I've had problems with files not appearing if you try to write outside your iPhone app's sandbox. It may be that you're getting the wrong Documents directory, and I've used the code above before.
other people have had similar issues and here, is your disctionary the mutable variety? try this code to do a simple test write. maybe its your dictionarys contents.
As for the NCSFDictionary class, this is the internal class used by the frameworks. sometimes you will notice these change if you have huge arrays dictionaries etc. apple uses optimised code and sometimes the back end storage object will change. but it is still your dictionary.
Shouldn't it be:
{
@"title" = @"A Movie";
@"time_length" = @"3:22";
},
{
@"title" = @"Another Movie";
@"time_length" = @"1:40";
},
{
@"title" = @"A Third Movie";
@"time_length" = @"2:10";
}
And don't forget to nil terminate it.
精彩评论