数据持久化之NSKeyedArchiver

         基本的数据类型如NSString、NSDictionary、NSArray、NSData、NSNumber等可以用属性列表的方法持久化到.plist 文件中,但如果是一些自定义的类的话,属性列表的方法就不管用了。archiver 方法可以做到。


编码如下:

     首先新建一个person类,定义它的三个属性,如下:

//
//  person.h
//  数据持久化之archiver
//
//  Created by Rio.King on 13-9-22.
//  Copyright (c) 2013年 Rio.King. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface person : UIView<NSCoding>
@property(nonatomic, assign) int age;
@property(nonatomic, copy)NSString *name;
@property(nonatomic, assign)float height;
@end

//
//  person.m
//  数据持久化之archiver
//
//  Created by Rio.King on 13-9-22.
//  Copyright (c) 2013年 Rio.King. All rights reserved.
//

#import "person.h"

@implementation person


#pragma mark 写入文件
-(void)encodeWithCoder:(NSCoder *)encoder{
    [super encodeWithCoder:encoder];//不要忘了这个
    [encoder encodeInt:self.age forKey:@"age"];
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeFloat:self.height forKey:@"height"];
}

#pragma mark 从文件中读取
-(id)initWithCoder:(NSCoder *)decoder{
    self = [super initWithCoder:decoder];//不要忘了这个
    self.age = [decoder decodeIntForKey:@"age"];
    self.name = [decoder decodeObjectForKey:@"name"];
    self.height = [decoder decodeFloatForKey:@"height"];
    
    
    return self;
}


-(NSString *)description{
    return [NSString stringWithFormat:@"name = %@, age = %d, height = %f",self.name,self.age,self.height];
}

//释放资源
-(void)dealloc{
    [super dealloc];
    [_name release];
}
@end

然后再ViewController.m文件中写如下代码:

//
//  ViewController.m
//  数据持久化之archiver
//
//  Created by Rio.King on 13-9-22.
//  Copyright (c) 2013年 Rio.King. All rights reserved.
//

#import "ViewController.h"
#import "person.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createPerson];
	[self readPerson];
}

//创建
-(void)createPerson{
    
    person *p = [[[person alloc] init] autorelease];
    p.age = 20;
    p.name = @"Rio";
    p.height =1.75f;
    
    //获得Document的路径
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];//拓展名可以自己随便取
    
    [NSKeyedArchiver archiveRootObject:p toFile:path];
    
}

//读取
-(void)readPerson{
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];
    person *person1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@",person1);
}

@end

,,在写ViewController.m文件代码的时候,必须在头文件中遵循NSCoding协议。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSCoding>

@end

运行结果如下:

2013-09-22 13:31:39.509 数据持久化之archiver[1080:c07] name = Rio, age = 20, height = 1.750000


注意事项



你可能感兴趣的:(ios,archiver持久化)