How do I serialize a simple object in iPhone sdk?

懵懂的女人 提交于 2019-12-02 15:36:11
Marc W

You do this in the same way you'd do it on Mac OS X: your POCOs must conform to the NSCoding protocol. See here for a conceptual reference, and here for the NSCoding reference.

If the data isn't that crazy extensive and you don't have ridiculously complicated relationships between your objects, writing everything out as a plist is probably your best option; it's very fast to execute and simple to implement in your code. Like you said, CoreData will probably be a lot of extra work to adapt your code to, and sqlite really is only good for storing data that's perfect to be stored in a relational database. Keep in mind that sqlite is also slower and uses more resources than working with binary plists.

To serialize custom object you just need to conform to the NSCoding protocol. If your object extends NSObject all you need to do (I believe) is to implement these (example for person object):

// Encode an object for an archive
- (void)encodeWithCoder:(NSCoder *)coder
{
    [super encodeWithCoder:coder];
    [coder encodeObject:name forKey:@“Name”];
    [coder encodeInteger:age forKey:@“Age”];
}
// Decode an object from an archive
- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    name = [[coder decodeObjectForKey:@“Name”] retain];
    age  = [coder decodeIntegerForKey:@“Age”];
}

NSArray and NSDictionary already implement methods for serialization. They will serialize all the objects that they hold (if objects implement NSCoder interface - they do if they extend NSObject). NSObject's encodeWithCoder and initWithCoder do nothing by default so unless you implement your own code in your classes nothing gets serialized.

If you have NSArray or NSDictionary of objects you can synchronize them using:

// Writing
- (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag;
- (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag;
// Reading
- (id)initWithContentsOfFile:(NSString *)aPath;
- (id)initWithContentsOfURL:(NSURL *)aURL;

NSCoder is the standard Cocoa idiom for serialization.

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