ios之归档demo

ios对自定义对象的归档。首先需要实现NSCoding与NSCopying接口

#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding, NSCopying>
@property (copy,nonatomic)NSString *name;
@property(assign,nonatomic)NSInteger age;
@end


需要重写接口的3个方法

#import "Person.h"

@implementation Person

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age =[aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}

//#pragma mark NSCoping
- (id)copyWithZone:(NSZone *)zone {
    Person *copy = [[[self class] allocWithZone:zone] init];
    copy.name = [self.name copyWithZone:zone];
    copy.age = self.age;
    return copy;
}

//////////////////////////////////////////

归档的两种方法:
(1)使用NSUserDefaults

// 保存
Person *person = [[Person alloc] init];
person.name = _text.text;
person.age = (NSInteger)[_age text];

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"person"];

// 读取
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"person"];
NSArray *books = [NSKeyedUnarchiver unarchiveObjectWithData:data];

 

(2)使用写文件

// 保存文件目录
-(NSString*) appStorgeLocation{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录
    return [documentsDirectory stringByAppendingPathComponent:@"lee0000"];
}

// 归档
Person *person = [[Person alloc] init];
person.name = _text.text;
person.age = (NSInteger)[_age text];

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:person forKey:@"kArchivingDataKey"]; //archivingDate的encodeWithCoder方法被调用
[archiver finishEncoding];
//写入文件
[data writeToFile:[self appStorgeLocation] atomically:YES];


// 读取
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self appStorgeLocation]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    
//获得类
Person *archivingData = [unarchiver decodeObjectForKey:@"kArchivingDataKey"];// initWithCoder方法被调用
[unarchiver finishDecoding];

 

posted on 2015-01-14 14:41  lee0oo0  阅读(280)  评论(0编辑  收藏  举报