-
归档也叫序列化,是将文件存在硬盘,解档是从硬盘还原
5种方式:
第一种、使用属性列表进行归档
如果对象是NSString,NSDictionary,NSArray,NSData或者NSNumber,可以使用writeToFile:atomically方法将数据写到文件,注意这种方式是明文
sample:
1234567NSArray *array = @[@
"abc"
,@
"123"
,
@23
.4];
if
([array writeToFile:@
"text.plist"
atomically:YES])
{
NSLog(@
"success"
);
}
NSArray *arr2=[NSArray arrayWithContentsOfFile:@
"text.plist"
];
NSLog(@
"%@"
,arr2);
第二、NSKeyedArchiver--对象归档,数据会加密
1、对于NSArray或者NSDictionary sample code:
1234567891011121314/***归档对象****/
NSArray *array = @[@
"abc"
,@
"123"
,
@23
.4];
NSString *homePath = NSHomeDirectory();
NSString *path = [homePath stringByAppendingPathComponent:@
"test.arc"
];
// BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:path];
BOOL success=[NSKeyedArchiver archiveRootObject:array toFile:path];
if
(success) {
NSLog(@
"archive success"
);
}
/***解归档****/
NSArray *array2 =[NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@
"%@"
,array2);
结果:success
2013-12-28 22:14:25.353 ArchiverDemo1[1206:303] (
abc,
123,
"23.4"
)
2、如果是其他类型的对象存储到文件,可以利用NSKeyedArchiver类创建带键的档案来完成
1234567891011121314151617181920212223NSString *homePath = NSHomeDirectory();
NSString *path = [homePath stringByAppendingPathComponent:@
"archiver2.archiv"
];
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
NSArray *array = @[@
"jack"
,@
"tom"
];
[archiver encodeInt:
100
forKey:@
"age"
];
[archiver encodeObject:array forKey:@
"names"
];
[archiver finishEncoding];
[archiver release];
BOOL success = [data writeToFile:path atomically:YES];
if
(success) {
NSLog(@
"archive success"
);
}
/***解归档对象**/
NSData *data2 = [NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data2];
int
age = [unArchiver decodeIntForKey:@
"age"
];
NSArray *names = [unArchiver decodeObjectForKey:@
"names"
];
[unArchiver release];
NSLog(@
"age=%d,names=%@"
,age,names);
对属性编码,归档的时候会调用
- (void)encodeWithCoder:(NSCoder *)aCoder
//对属性解码,解归档调用
- (id)initWithCoder:(NSCoder *)aDecoder
1234567891011121314151617181920//对属性编码,归档的时候会调用
- (
void
)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInt:_age forKey:AGE];
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeObject:_email forKey:EMAIL];
[aCoder encodeObject:_password forKey:PASSWORD];
}
//对属性解码,解归档调用
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [
super
init];
if
(self != nil) {
_age = [aDecoder decodeIntForKey:AGE];
self.name = [aDecoder decodeObjectForKey:NAME];
self.email = [aDecoder decodeObjectForKey:EMAIL];
self.password = [aDecoder decodeObjectForKey:PASSWORD];
}
return
self;
}
第三种:NSUserDefaultssample code:
12[[NSUserDefaults standardUserDefaults] setObject:authData forKey:@
"SinaWeiboAuthData"
];
[[NSUserDefaults standardUserDefaults] synchronize];
第四种、SQlite数据库、CoreData数据库