标签:style blog color io 使用 ar for 文件 数据
一、使用XML属性列表归档
此方法适用于NSString、NSDictionary、NSarray、NSDate、NSnumber,其中atomically参数表示先将字典写入临时备份文件,成功之后,把最终数据写入到dic指定的文件中
1 #import <Foundation/Foundation.h> 2 3 int main(int argc, const char * argv[]) 4 { 5 6 @autoreleasepool { 7 //生成字典dic,并将字典dic写到xml文件myFirstDic文件 8 NSDictionary *dic = @{@"wukong": @"so smart", @"ranHanLu": @"so beautiful", @"family": @"best importtant!"}; 9 if ([dic writeToFile: @"myFirstDic" atomically:YES] == NO) { 10 NSLog(@"Write to file failed"); 11 } 12 13 //读取 14 dic = [NSDictionary dictionaryWithContentsOfFile: @"myFirstDic"]; 15 for (NSString *key in dic) { 16 NSLog(@"key is: %@, value is : %@", key, dic[key]); 17 } 18 } 19 return 0; 20 }
二、适用NSKeyedUnarchiver类中得archiveRootObject:方法存储字典
此方法可直接用于将NSString、NSDictionary、NSarray、NSDate、NSnumber归档,要适用于所有对象,需要对重写encodeWithCoder和initWithCoder方法,见三
1 #import <Foundation/Foundation.h> 2 3 int main(int argc, const char * argv[]) 4 { 5 6 @autoreleasepool { 7 //适用NSKeyedUnarchiver类中得archiveRootObject:方法存储字典 8 9 NSDictionary *dic = @{ 10 @"wukong": @"so smart", @"ranHanLu": @"so beautiful", @"archive": @"ending...." 11 }; 12 [NSKeyedArchiver archiveRootObject: dic toFile: @"dic.archive"]; 13 14 //读取 15 NSDictionary *new; 16 new = [NSKeyedUnarchiver unarchiveObjectWithFile: @"dic.archive"]; 17 for (NSString *key in new) { 18 NSLog(@"key is: %@, value is : %@", key, new[key]); 19 } 20 21 } 22 return 0; 23 }
三、适用NSKeyedUnarchiver类中得archiveRootObject:方法,存储任意对象
1.首先需要对自定义对象添加协议方法 1 #import <Foundation/Foundation.h>
1 #import <Foundation/Foundation.h> 2 3 @interface testClass: NSObject 4 5 @property (copy, nonatomic) NSString *name, *address; 6 @end 7 8 @implementation testClass 9 //添加encodeWithCoder和initWithCoder方法 10 -(void) encodeWithCoder: (NSCoder *) encoder 11 { 12 [encoder encodeObject: name forKey: @"testClassName"]; 13 [encoder encodeObject: address forKey: @"testClassAddress"]; 14 } 15 16 -(id) initWithCoder: (NSCoder *) decoder 17 { 18 name = [decoder decodeObjectForKey: @"testClassName"]; 19 address = [decoder decodeObjectForKey: @"testClassAddress"]; 20 21 return self; 22 } 23 @synthesize name, address; 24 25 @end 26 int main(int argc, const char * argv[]) 27 { 28 29 @autoreleasepool { 30 testClass *myTest = [[testClass alloc] init]; 31 32 myTest.name = @"wukong"; 33 myTest.address = @"sichuan"; 34 //归档 35 [NSKeyedArchiver archiveRootObject: myTest toFile: @"myTest.archive"]; 36 //读出 37 myTest = [NSKeyedUnarchiver unarchiveObjectWithFile: @"myTest.archive"]; 38 NSLog(@"Name is : %@, address is : %@", myTest.name, myTest.address); 39 40 } 41 return 0; 42 }
标签:style blog color io 使用 ar for 文件 数据
原文地址:http://www.cnblogs.com/pretty-guy/p/3958366.html