problem writing a NSMutableArray to file in cocoa

匆匆过客 提交于 2019-12-04 13:47:40

问题


A real beginners question. I have a NSView subclass in which I create a NSMutableArray containing NSValues. When I want to write the array to a file using writetofile:atomatically: the file is created but it contains none of the NSValues that the mutable array does contain. Does anyone know how I successfully can write this mutable array to a file?

Thanks


回答1:


NSValues can't be saved in a plist (which is what writeToFile:atomically: does). Take a look here for the values you can save. (NSNumber is a kind of NSValue you can save, but other NSValues will fail.)

If you want to save your array with NSValues, you can use archiving instead of writeToFile:atomically:. NSArray and NSValue both support archiving, so you just convert the array to an archive and save that data to a file. (It will include the NSValues as well.) The code looks something like this:

[NSKeyedArchiver archiveRootObject:myArray toFile:@"myPath"];

To load it, just use:

NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:@"myPath"];


来源:https://stackoverflow.com/questions/751093/problem-writing-a-nsmutablearray-to-file-in-cocoa

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