How do I serialize a simple object in iPhone sdk?

后端 未结 3 1862
清歌不尽
清歌不尽 2021-01-30 14:19

I have a dictionary of objects; they are all POCO objects that should be serializable. What technique should I look at for writing these to disk. I\'m looking for the simplest

3条回答
  •  太阳男子
    2021-01-30 14:59

    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;
    

提交回复
热议问题