views:

2788

answers:

2

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

+4  A: 

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"];
Jesse Rusak
I used NSArchiver and NSUnarchiver instead and it works perfectly. Thanks
You're welcome. Note that NSKeyed[Un]Archiver is preferred over NS[Un]Archiver nowadays.
Jesse Rusak
A: 

I have a similar problem with an NSMutableArray which holds NSPoints wrapped as NSValues. I get the same error message when I use the code suggested above. Am thinking of creating my own "point" class to get round the problem.

Model objects are always an improvement; definitely do that. However, it won't solve your problem—you still can't use -[NSArray writeToFile:atomically:] to write out anything but a pure property list, and neither NSValue nor your model class is a property list type. You'll still need to use NSKeyed{A,Una}rchiver, as suggested by the accepted answer.
Peter Hosey
I was going implement NSCoding and include en/decodeFloat:forKey: in the encodeWithCoder: / initWithCoder methods. ie my "points"class would know how to archive itself. Am I on the right path or completely screwed up?