1 #import <Foundation/Foundation.h> 2
//记得要遵守<NSCoding>协议
> 3 @interface person : NSObject<NSCoding> 4 @property(nonatomic,copy)NSString *name; 5 @property(nonatomic,assign)int age; 6 @end
1 #import "person.h" 2 3 @implementation person 4 -(void)encodeWithCoder:(NSCoder *)aCoder{ 5 [aCoder encodeObject:_name forKey:@"name"]; 6 [aCoder encodeInt:_age forKey:@"age"]; 7 } 8 -(id)initWithCoder:(NSCoder *)aDecoder{ 9 if (self =[super init]) { 10 _name =[aDecoder decodeObjectForKey:@"name"]; 11 _age =[aDecoder decodeIntForKey:@"age"]; 12 } 13 14 return self; 15 } 16 @end
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 5 6 @end
1 #import "ViewController.h" 2 #import "person.h" 3 @interface ViewController () 4 5 @end 6 7 @implementation ViewController 8 //存数据 9 - (IBAction)save:(id)sender { 10 //获取临近的目录 11 NSString *tmpPath =NSTemporaryDirectory(); 12 NSString *filePath =[tmpPath stringByAppendingPathComponent:@"person.data"]; 13 person *p =[[person alloc] init]; 14 p.name =@"天桥"; 15 p.age =18; 16 [NSKeyedArchiver archiveRootObject:p toFile:filePath]; 17 }
//取数据 18 - (IBAction)read:(id)sender { 19 NSString *tmpPath =NSTemporaryDirectory(); 20 NSString *filePath =[tmpPath stringByAppendingPathComponent:@"person.data"];
//记得给解档属性进行赋值
21 person * p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; 22 NSLog(@"%@,%d",p.name,p.age); 23 24 }
原文:http://www.cnblogs.com/lxlmq412/p/4839785.html