NSDictionary writeToFile

孤人 提交于 2019-12-04 19:16:18

问题


Is there a size limit to saving dictionaries?

I am attempting to write a rather large dictionary with around 100 keys with nested dictionaries using writeToFile: but it never writes and is always false.

Is this a limitation or am I doing something incorrect,

The code i use is the following.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *fullPath = [documentsDir stringByAppendingPathComponent:@"test.plist"];   

[myDict writeToFile: fullPath  atomically:YES];

回答1:


There is no size limit (save for memory and disk space).

What are the contents of myDict?

If it is anything but the small set of classes allowed in property lists, then you can't use writeToFile:atomically:.

Either you would need to limit your dictionary to only containing instances of those classes or you will need to use a different archiving method.

In particular, a lot of the JSON libraries will spew NSNULL instances into the collections. Those can't be archived. You need to either edit them out or replace them with objects that can be archived.

Of relevance:

http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html

http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i




回答2:


There is one more trick to this, besides using only eligible objects (instances of NSNumber, NSString, NSData etc) the keys have to be NSString objects. Normally you can use any object for NSDictionary key but to have a successful writeToFile: the keys in the NSDictionary need to be instances NSString.




回答3:


I would add one more trick as well that I ran into on Lion. The folder that you want to write the plist to must exist before you call NSDictionary's writeToFile:atomically:. You can use NSFileManager to test existence and create a new folder if necessary.




回答4:


I had this, as is mentioned by others the dictionary can not be saved with some data types (notable NULLs).

Because my dictionary was from a server (in form of JSON) I could not guarantee what was in it so I saved the RAW data (from the dataWithContentsOfURL) before serialization of the JSON. To this end I am guessing you could convert the dict to NSData and save that - something like;

NSData *convetedData = [NSKeyedArchiver archivedDataWithRootObject:JSONDict];

And then later retrieve and convert back like this.

NSDictionary *JSONDict = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:convertedDATA];


来源:https://stackoverflow.com/questions/3460016/nsdictionary-writetofile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!