iOS Data Serialization & Archive

iOS Data Serialization: NSPropertyListSerialization

The NSPropertyListSerialization class converts property list to and from several serialized forms

  • Property list objects include NSData, NSString, NSArray, NSDictionary, NSDate, and NSNumber objects

Creating a NSData from a plist

+ (NSData *)dataFromPropertyList:(id)plist
                          format:(NSPropertyListFormat)format
                         options:(NSPropertyListWriteOptions)options
                           error:(NSError **)error;
  • format supports XML or binary

Creating a plist from an NSData

+ (id)propertyListWithData:(NSData *)plist
       options:(NSPropertyListReadOptions)options
        format:(NSPropertyListFormat *)format
         error:(NSError **)error;

To write data into a file with the NSData class method

+ (BOOL)writeToURL:(NSURL *)fileURL atomically:(BOOL)atomically;
  • atomically - when it is true, a temp file is created and then move to provide atomic operation

To read data from a file with the NSData class method

+ initWithContentsOfURL:(NSURL *)aURL;

iOS Archiving - Data Serialization with Complex Objects

To archive a hierarchy object tree

  • Object needs to implement
    - (void)encodeWithCoder:(NSCoder *)coder {
        [super encodeWithCoder:coder];
        [coder encodeFloat:value forKey:@"value"];
        [coder encodeObject:object1 forKey:@"object1"];
    }
    
    - initWithCoder:(NSCoder *)coder {
        self = [super initWithCoder:coder];
        value = [coder decodeFloatForKey:@"value"];
        object1 = [coder decodeObjectForKey:@"object1"];
    }
    

Use NSKeyedArchiver to archive/un-archive data

+ (NSData *)archivedDataWithRootObject:(id <NSCoder>)rootObject;
+ (id <NSCoder>)unarchiveObjectWithData:(NSData *)data;