- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:name forKey:@"MY_NAME"];
[aCoder encodeInt32:age forKey:@"MY_AGE"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if(self)
{
name = [aDecoder decodeObjectForKey:@"MY_NAME"];
age = [aDecoder decodeIntForKey:@"MY_AGE"];
}
return self;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSString *path = [self filePath:@"test.txt"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
MyObject *obj = [unarchiver decodeObjectForKey:@"MY_OBJ"];
[unarchiver finishDecoding];
NSLog(@"name %@ age %d color %@", obj.name, obj.age,
obj.color);
}
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSString *path = [self filePath:@"test.txt"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSLog(@"file exist");
}
else
{
NSLog(@"create file");
MyObject *myObj = [[MyObject alloc] init];
myObj.name = @"peter";
myObj.age = 18;
myObj.color = @"blue";
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:myObj forKey:@"MY_OBJ"];
[archiver finishEncoding];
[data writeToFile:path atomically:YES];
}
}