您的位置:首页 > 移动开发 > Objective-C

Object-C 归档、解档

2016-04-20 16:24 288 查看
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

归档(NSKeyedArchiver)/解档(NSKeyedUnarchiver)

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

归档--》

NSArray *arr = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];

NSMutableData * data = [NSMutableData data];

NSKeyedArchiver * arc = [NSKeyedArchiver alloc] initForWritingWithMutableData:data];

[arc encodeWithObjects:arr forKey:@"array"];

[arc encodeWithInt:100 forKey:@"age"];

[arc encodeWithObject:@"hello world" forKey:@"name"];

[arc finishEncoding];

[arc release];

NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"arc.txt"];

BOOL success = [data writeToFile:filePath atomically:YES];//success YES 归档成功

文件解档-------------》

NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"arc.txt"];

NSData * data = [[ NSData alloc] initWithContentsOfFile:path];

NSKeyedUnarchiver * unarc =[ [NSKeyedUnarchiver alloc] initForReadingWithData:data];

NSArray * arr = [unarc decodeObjectForKey:@"array"];

int age = [unarc decodeIntForKey:@"age"];

NSString *name = [unarc decodeObjectForKey:@"name"];

[data release];

[unarc release];

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

对象的归档、解档

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

类似java实现接口一样,OC实现NSCoding协议

重写两个方法:initWithCoder:NSCoder * 和 encodeWithCoder:NSCoder *

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

  self = [super init];

  if(self){

self.name = [aDecoder decodeObjectForKey:@"name"];

    self.age = [aDecoder decoderObjectForKey:@"age"];

    self.number = [aDecoder decoderObjectForKey:@"number"];

    

  }

return self;

}

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

[aCoder encodeObject:_name forKey:@"name"];

[aCoder encodeInteger:_age forKey:@"age"];

[aCoder encodeObject:_number forKey:@"number"];

}

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

per.name = @"hello";

per.age = 12;

per.number = @"10086";

NSString *path = [NSHomeDirectory stringByAppendingPathComponent:@"persion.plist"];

BOOL success = [NSKeyedArchiver archiveRootObject:per toFilePath:path];

 [per release];

//解档对象

 Person * per = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

 

--》

解档
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: