Archives and serializations are two ways in which you can create architecture-independent byte streams of hierarchical data. Byte streams can then be written to a file or transmitted to another process, perhaps over a network. When the byte stream is decoded, the hierarchy is regenerated. Archives provide a detailed record of a collection of interrelated objects and values. Serializations record only the simple hierarchy of property-list values.
In English, it means, you can write a NSArray directly to a file and read it back when you need.
By using serializations you can directly write NSArray, NSDictionaries, NSObjects or even your own custom objects to the file.
NSArray *arr = [NSArray arrayWithObjects:@"Obj1", @"Obj2", @"Obj3", @"Obj4", nil];
[NSKeyedArchiver archiveRootObject:arr toFile:[[self getApplicationsDirectory] stringByAppendingPathComponent:@"encodedFile"]];
You can simply regenerate them by using the NSKeyedUnarchiver class.
NSData *readedData = [NSData dataWithContentsOfFile:[[self getApplicationsDirectory] stringByAppendingPathComponent:@"encodedFileData"]];
NSArray *decodeObj = [NSKeyedUnarchiver unarchiveObjectWithData:readedData];
All of the Foundation value objects objects (NSString, NSArray, NSNumber, and so on) and most of the UIKit user interface objects adopt NSCoding and can be put into an archive.
For custom objects you have to implement the NSCoding protol.
I have created a sample application to show the working of this. You can find it here
WIKI is here:
NSArchiver Docs link is here:
No comments:
Post a Comment