数据持久化之一

简单对象(NSString,NSData,NSDictionary,NSArray以及他们的子类)的本地持久化,通过writeToFile写入到文件内
复杂对象(简单对象以外,如自定义Person类等)的本地持久化,先将复杂对象转为NSData(这就叫归档),然后writeToFile写入到文件内;

首先简单对象本地持久化步骤:

NSDictionary,NSArray类型数据操作步骤类似;

NSData类型数据步骤如下:

 

复杂对象本地持久化步骤:

#pragma mark - 复杂对象的本地化-------自定义Person类
    //1.找到Documents文件夹的目录
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //2.创建Person对象
    Person *per= [[Person alloc] init];
    per.name = @"HHHBoy";
#pragma mark 归档
    //3.1创建一个NSMutableData,用于初始化归档工具的
    NSMutableData *data = [NSMutableData data];
    //3.2创建归档工具
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //3.3对要归档的person对象进行归档
    [archiver encodeObject:per forKey:@"person"];
    //3.4结束归档
    [archiver finishEncoding];
    //4.将归档的内容NSMutableData存储到本地
    NSString *personPath = [documentPath stringByAppendingPathComponent:@"person.plist"];
    [data writeToFile:personPath atomically:YES];
    NSLog(@"%@", personPath);
#pragma mark - 解档
    //1.将要解档的数据找出来
    NSData *resultData = [NSData dataWithContentsOfFile:personPath];
    //NSLog(@"resultData = %@", resultData);
    //2.创建解档工具
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:resultData];
    //3.对person对象进行解档[要使用对象接收]
    Person *newPer = [unarchiver decodeObjectForKey:@"person"];
    //4.结束解档
    [unarchiver finishDecoding];

 其中自定义类中的.m文件中为:

@implementation Person

//将所有的属性进行归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.gender forKey:@"gender"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
//解档(反归档)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.gender = [aDecoder decodeObjectForKey:@"gender"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}
@end

 

posted @ 2016-05-12 18:55  吾悠南山  阅读(159)  评论(0编辑  收藏  举报