歸檔也叫序列化,是將文件存在硬盤,解檔是從硬盤還原
5種方式:
第一種、使用屬性列表進行歸檔
如果對象是NSString,NSDictionary,NSArray,NSData或者NSNumber,可以使用writeToFile:atomically方法將數據寫到文件,注意這種方式是明文
sample:
NSArray *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:
/***歸檔對象****/ 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類創建帶鍵的檔案來完成
NSString *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
//對屬性編碼,歸檔的時候會調用 - (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; }
sample code:
[[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"]; [[NSUserDefaults standardUserDefaults] synchronize];
第四種、SQlite數據庫、CoreData數據庫