save Objects to Files

来源:互联网 发布:mac新系统sierra 编辑:程序博客网 时间:2024/04/28 19:32

1。将对象保存到磁盘文件中:该对象必须实现<NSCoding>协议

   - (void)encodeWithCoder:(NSCoder *)aCoder;

   - (instancetype)initWithCoder:(NSCoder *)aDecoder;

   NSKeyedArchiver:归档、存档,将对象读入(保存到磁盘文件中)

   NSKeyedUnarchiver:解档,将对象取出(从磁盘文件中取出)

e.g.

@interface Person : NSObject <NSCoding>

    @property (nonatomic, copy) NSString *firstName;

    @property (nonatomic, copy) NSString *lastName;

@end

//=============

#import "Person.h"

NSString *const kFirstNameKey = @"FirstNameKey";

NSString *const kLastNameKey = @"LastNameKey";

@implementation Person

- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:self.firstNameforKey:kFirstNameKey];

    [aCoder encodeObject:self.lastName forKey:kLastNameKey];

}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{

    self = [super init];

    if (self != nil){

        _firstName = [aDecoder decodeObjectForKey:kFirstNameKey];

        _lastName = [aDecoder decodeObjectForKey:kLastNameKey];

    }

    return self;

}

@end

//============

-(void)actionSave{

    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"steveJobs.txt"];   

    /* 初始化对象 */

    Person *steveJobs = [[Person alloc] init];

    steveJobs.firstName = @"Steven";

    steveJobs.lastName =@"Jobs";    

    /* 归档 */

    [NSKeyedArchiver archiveRootObject:steveJobs toFile:filePath];    

    /* 解档*/

    Person *cloneOfSteveJobs = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    if (cloneOfSteveJobs !=nil) {

        NSLog(@"Person:first Name:%@,last Name:%@",cloneOfSteveJobs.firstName,cloneOfSteveJobs.lastName);

    }   

    /* 删除归档时的文件 */

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    [fileManager removeItemAtPath:filePath error:nil];

}



0 0
原创粉丝点击