//属性列表的方式,只能存系统定义的类型
NSArray *array1 = [NSArray arrayWithContentsOfFile:@"/Users/apple/Desktop/test.plist"];
NSLog(@"%@", array1);
//1. 只能存系统定义的类型
//2. 不能存太多数据或者是大数据
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];//单(实)例类
[userDefault setInteger:2340 forKey:@"age"];
//
NSInteger age = [userDefault integerForKey:@"age"];
NSLog(@"%d", age);
NSString *str = @"123abc";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", data);
data = [NSData dataWithContentsOfFile:@"/Users/apple/Desktop/a.out"];
NSLog(@"%@", data);
NSMutableData *mData = [NSMutableData data];
[mData appendData:data];
[mData appendData:data];
[mData writeToFile:@"/Users/apple/Desktop/b.out" atomically:YES];
NSURL *url = [NSURL URLWithString:@"http://sqlite.org/images/foreignlogos/nokia.gif"];
NSData *nokia = [NSData dataWithContentsOfURL:url];
[nokia writeToFile:@"/Users/apple/Desktop/nokia.gif" atomically:YES];
}
NSString *str = @"abc";//把abc存入str
[NSKeyedArchiver archiveRootObject:str toFile:@"/Users/apple/Desktop/test.plist"];//归档
NSString *str1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/apple/Desktop/test.plist"]; //解档
NSLog(@"%@", str1);
Student *stu = [[Student alloc] init]; //自定的类需要实现协议
stu.name = @"Zhangsan";
stu.age = 30;
//@protocol NSCoding //自定义的类归档解档需要实现此协议
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;//
[NSKeyedArchiver archiveRootObject:stu toFile:@"/Users/apple/Desktop/student.plist"];
Student *stu1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/apple/Desktop/student.plist"];
NSLog(@"%p, %p", stu, stu1);
NSLog(@"%@:%d, %@:%d", stu.name, stu.age, stu1.name, stu1.age);
//stu->path->stu1
NSData *stuData = [NSKeyedArchiver archivedDataWithRootObject:stu];//把数据存入NSData
[stuData writeToFile:@"/Users/apple/Desktop/stu.plist" atomically:YES];//归档
NSData *stuData2 = [NSData dataWithContentsOfFile:@"/Users/apple/Desktop/stu.plist"];
Student *stu3 = [NSKeyedUnarchiver unarchiveObjectWithData:stuData2];//解档
NSLog(@"%@:%d---%@:%d", stu.name, stu.age, stu3.name, stu3.age);
// stu->stuData->path->stuData2->stu3
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];//另外一种方式取值
[userDefault setObject:stuData forKey:@"xxxx"];//xxxx就等同于stuData
NSData *stuData3 = [userDefault objectForKey:@"xxxx"]; //中间通过data多一步转换
Student *stu4 = [NSKeyedUnarchiver unarchiveObjectWithData:stuData3];
NSLog(@"%@:%d", stu4.name, stu4.age);
协议的实现如下
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:kNameKey];
[aCoder encodeInteger:_age forKey:kAgeKey];
[aCoder encodeObject:_dog forKey:kDogKey];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:kNameKey];
self.age = [aDecoder decodeIntegerForKey:kAgeKey];
self.dog = [aDecoder decodeObjectForKey:kDogKey];
}