Object-c归档使用

来源:互联网 发布:可口可乐表白软件 编辑:程序博客网 时间:2024/05/01 00:05

1 使用XML归档

MAC OS X使用XML文档存储默认参数、应用程序设置和配置信息。

NSString、NSDictionary、NSArray、NSData或NSNumber类型,可以通过writeToFile:atomically方法将数据写到文件中。字典和数组可以使用XML格式写数据。

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:    @"letter A",@"A",@"letter B",@"B",@"letter C",@"C",nil];if([dict writeToFile:@"dict" atomically:YES]==NO){    NSLog(@"写入失败");}

这里将数据写入到dict文件中,atomically的属性YES,表示先将数据库写入到临时备份文件,成功后,即把数据写入到文件中。

读取文件内容可以使用:

dictionaryWithContentsOfFile;arrayWithContentsOfFile;dataWithContentsOfFile;StringWithContentsOfFile;

2 NSKeyedArchiver

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:    @"letter A",@"A",@"letter B",@"B",@"letter C",@"C",nil];[NSKeyedArchiver archiveRootObject:dict toFile:@"dict.archive"];[NSKeyedUnarchiver unarchiveObjectWithFile:@"dict.archive"];for(NSString *str in dict){    NSLog(@"%@:%S",str,[dict objectForKey:str]);}

3 编码和解码

在使用NSKeyedArchiver归档Student对象时(student对象时自定义的对象),Student对象需实现NSCoding协议,添加encodeWithCoder编码方法和initWithCoder解码方法。

//encode-(void) encodeWithCoder:(NSCoder*) coder{    [coder encodeObject:name forKey:@"stu_name"];    [coder encodeObject:email forKey:@"stu_email"];}//decode-(id) initWithCoder:(NSCoder*) coder{    name = [coder decodeObjectforKey:@"stu_name"];    email = [coder decodeObjectforKey:@"stu_email"];}

基本类型的编码和解码:

encodeBool:forKey decodeBool:forKeyencodeInt:forKeydecodeInt:forKeyencodeInt32:forKeydecodeInt32:forKeyencodeInt64:forKeydecodeInt64:forKeyencodeFloat:forKeydecodeFloat:forKeyencodeDouble:forKeydecodeDouble:forKey


4 使用NSData创建自定义档案

使用NSData可以自定义归档各种对象。前提是对象实现encodeObject:forKey和initWithObjcetforKey。

NSMutableData *data = [NSMutableData data];  //创建一个可变的数据空间NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [arch encodeObject:stu1 forKey:@"stu"];[arch encodeObject:book forKey:@"book"];[arch finishEncoding]; [data writeToFile:@"test" atomically:YES];

5 使用归档深度复制

可以先对一个对象归档,然后解码后,使用另一个引用指向解码后的对象实现归档。整个过程可以不用使用文件,直接发生在内存中。

NSData *data;NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"one",@"two",@"three",nil];NSMutableArray *arr2; data = [NSKeyedArchiver archiveDataWithRootObject:arr1];arr2 = [NSKeyedArchiver unarchiveObjectWithData:data];

 

0 0
原创粉丝点击