NSKeyedArchiver编码器

ViewController.m文件

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",NSHomeDirectory());
    NSData *data = [NSData dataWithContentsOfFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/peopleFile.plist"]];
        //NSKeyedUnarchiver解码器,能够把二进制数据解码为对象。
    People *p = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSLog(@"%@",p);
}

- (IBAction)savePeopleClick:(UIButton *)sender {
    
    People *p1 = [[People alloc] init];
    p1.name = @"张三";
    p1.age = 34;
    p1.sex = YES;
    
        //NSUserDefaults中只能存储系统自带的数据类
        //[[NSUserDefaults standardUserDefaults] setObject:p1 forKey:@"people"];

        //只有数组中存储的对象是系统自带的数据类(NSString,NSArray,NSNumber,NSDate)时,数组才可以writoFile.
//    NSArray *array = [NSArray arrayWithObject:p1];
//    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/arrayFile.plist"];
//    if ([array writeToFile:path atomically:NO]) {
//        NSLog(@"存储成功");
//    }else {
//        NSLog(@"存储失败");
//    }
    
        //NSData数据类,表示一段二进制数据。
        //对于自定义的类,要想存入文件,必须把对象转换为二进制数据。就必须实现NSCoding协议。(对象序列化)
    
        //NSKeyedArchiver,编码器,能够把一个对象转换为二进制数据(前提是这个对象实现了NSCoding协议)
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p1];
        //二进制数据可以直接写入文件
    [data writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/peopleFile.plist"] atomically:NO];
}
People.h

//只有声明并实现了NSCoding的类才能被转换为二进制数据。
@interface People : NSObject<NSCoding>

@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)NSInteger age;
@property (nonatomic,assign)BOOL sex;

People.m

- (void)dealloc{
        //[_name release];
    self.name = nil;
    [super dealloc];
}

    //编码方法,方法中要把需要编码的属性进行编码。
- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
    [aCoder encodeBool:_sex forKey:@"sex"];
}
    //解码方法,把每个属性进行解码
- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
            //self.name = [aDecoder decodeObjectForKey:@"name"];
        _name = [[aDecoder decodeObjectForKey:@"name"] copy];
        _age = [aDecoder decodeIntegerForKey:@"age"];
        _sex = [aDecoder decodeBoolForKey:@"sex"];
    }
    return self;
}

- (NSString *)description{
    return [NSString stringWithFormat:@"%@,%lu,%@",_name,_age,_sex?@"男":@"女"];
}


你可能感兴趣的:(NSKeyedArchiver)