Created
June 18, 2011 14:51
-
-
Save rabinjoshi/1033156 to your computer and use it in GitHub Desktop.
Archiving objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.m | |
// Archiving3 | |
// | |
// Created by Rabin Joshi on 6/18/11. | |
// Copyright 2011 Techgene. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#import "Foo.h" | |
#import "Bar.h" | |
int main (int argc, const char * argv[]) | |
{ | |
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; | |
// insert code here... | |
NSLog(@"Hello, World!"); | |
/* | |
NSMutableData *dataArea; | |
NSKeyedArchiver *archiver; | |
Foo *myFoo1 = [[Foo alloc] init]; | |
Bar *myBar1 = [[Bar alloc] init]; | |
//Foo *myFoo2; | |
//Bar *myBar2; | |
[myFoo1 setStrVal: @"This is the string"]; | |
[myFoo1 setIntVal: 12345]; | |
[myFoo1 setFloatVal: 98.6]; | |
[myBar1 setStrVal: @"This is another string"]; | |
[myBar1 setIntVal: 67890]; | |
[myBar1 setFloatVal: 12.3]; | |
// Set up a data area and connect it to an NSKeyedArchiver object | |
dataArea = [NSMutableData data]; | |
archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData: dataArea]; | |
// Now we can begin to archive objects | |
[archiver encodeObject: myFoo1 forKey: @"myFoo1"]; | |
[archiver encodeObject: myBar1 forKey: @"myBar1"]; | |
[archiver finishEncoding]; | |
// Write the archived data are to a file | |
if ( [dataArea writeToFile: @"/Users/rabinjoshi/Desktop/myArchive.plist" atomically: YES] == NO) | |
NSLog (@"Archiving failed!"); | |
[archiver release]; | |
*/ | |
//Unarchiving | |
NSMutableData *dataArea2; | |
NSKeyedUnarchiver *unarchiver; | |
Foo *myFoo2; | |
Bar *myBar2; | |
dataArea2 = [NSData dataWithContentsOfFile:@"/Users/rabinjoshi/Desktop/myArchive.plist"]; | |
if (! dataArea2) { | |
NSLog (@"Can’t read back archive file!"); | |
//Return (1); | |
} | |
unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData: dataArea2]; | |
// Decode the objects we previously stored in the archive | |
myFoo2 = [unarchiver decodeObjectForKey: @"myFoo1"]; | |
myBar2 = [unarchiver decodeObjectForKey: @"myBar1"]; | |
[unarchiver finishDecoding]; | |
[unarchiver release]; | |
// Verify that the restore was successful | |
NSLog (@"%@ \n %i \n %g", [myFoo2 strVal], [myFoo2 intVal], [myFoo2 floatVal]); | |
NSLog (@"%@ \n %i \n %g", [myBar2 strVal], [myBar2 intVal], [myBar2 floatVal]); | |
[pool drain]; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment