在.h文件
#import <Foundation/Foundation.h>
//NSCoding编码协议,只有实现了编码协议的类才能够进行对象序列化
@interface People : NSObject<NSCoding>
@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)int age;
@property (nonatomic,assign)BOOL sex;
- (void)save;
@end
代码是实现在.m文件
#import "People.h"
@implementation People
- (void)dealloc{
self.name = nil;
[super dealloc];
}
//编码方法,把所有的属性进行编码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInt:_age forKey:@"age"];
[aCoder encodeBool:_sex forKey:@"sex"];
}
//解码方法,初始化这个对象,然后解码属性进行赋值
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntForKey:@"age"];
self.sex = [aDecoder decodeBoolForKey:@"sex"];
}
return self;
}
- (void)save{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *paths = [path stringByAppendingPathComponent:@"a.plist"];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
[data writeToFile:paths atomically:YES];
}