Can I serialize an array in Objective-C and have all of its values still be intact when I deserialize it?
So if I have an array with values A, B, and C, can I serialize it and dese开发者_如何学Crialize it with the values still intact or is there a more efficient way of serializing/deserializing an array? Could you explain how to do this?
For those instances where there are array contents that are not supported by a plist use the NSCoding protocol. Implement -(void)encodeWithCoder:(NSCoder*)encoder
and -(id)initWithCoder:(NSCoder*)decoder
They are really quite simple.
To archive:
[NSKeyedArchiver archiveRootObject:myObjectToArchive toFile:myFilePath];
and to recreate:
MyClass myInstance = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilePath];
There are built-in methods to serialize it. So you can deserialize an array from a file with
- (id)initWithContentsOfFile:(NSString *)aPath
- (id)initWithContentsOfURL:(NSURL *)aURL
and save it to a file with
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
- (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag
These will save it as a .plist file, which the current values intact. This is probably the easiest way to serialize and deserialize an array.
If your array has objects that do not conform to the NSCoding protocol though, you will need to implement that.
精彩评论