Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. - (void)encodeWithCoder:(NSCoder *)aCoder
  2. {
  3.     [aCoder encodeObject:name forKey:@"MY_NAME"];
  4.     [aCoder encodeInt32:age forKey:@"MY_AGE"];
  5.  
  6. }
  7.  
  8. -(id)initWithCoder:(NSCoder *)aDecoder
  9. {
  10.     self = [super init];
  11.     if(self)
  12.     {
  13.         name = [aDecoder decodeObjectForKey:@"MY_NAME"];
  14.         age = [aDecoder decodeIntForKey:@"MY_AGE"];
  15.  
  16.     }
  17.     return self;
  18. }
  19.  
  20. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  21. {
  22.     // Override point for customization after application launch.
  23.     NSString *path = [self filePath:@"test.txt"];
  24.     if ([[NSFileManager defaultManager] fileExistsAtPath:path])
  25.     {
  26.         NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
  27.         NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  28.         MyObject *obj = [unarchiver decodeObjectForKey:@"MY_OBJ"];
  29.         [unarchiver finishDecoding];
  30.     NSLog(@"name %@ age %d color %@", obj.name, obj.age,
  31.               obj.color);
  32.     }
  33.     return YES;
  34. }
  35.  
  36. - (void)applicationDidEnterBackground:(UIApplication *)application
  37. {
  38.     NSString *path = [self filePath:@"test.txt"];
  39.     if ([[NSFileManager defaultManager] fileExistsAtPath:path])
  40.     {
  41.         NSLog(@"file exist");
  42.     }
  43.     else
  44.     {
  45.         NSLog(@"create file");
  46.         MyObject *myObj = [[MyObject alloc] init];
  47.         myObj.name = @"peter";
  48.         myObj.age = 18;
  49.         myObj.color = @"blue";
  50.     NSMutableData *data = [[NSMutableData alloc] init];
  51.         NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  52.         [archiver encodeObject:myObj forKey:@"MY_OBJ"];
  53.         [archiver finishEncoding];
  54.         [data writeToFile:path atomically:YES];
  55.     }
  56. }