problem writing a NSMutableArray to file in cocoa

2020-06-04 06:01发布

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条回答
叛逆
2楼-- · 2020-06-04 06:26

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"];
查看更多
登录 后发表回答