一. 使用NSKeyedArchiver类操作对象的存取
特点:该类可以将对象以键值对的形式存入文件,并通过key从文件中取出,与android中的SharedPreference用法类似,而且它序列化后的数据是加密的
1. 将数据存入文件:
- NSString *rootDir = NSHomeDirectory();
- NSString *path = [rootDir stringByAppendingPathComponent:@"test.txt"];
- NSMutableData *data = [NSMutable data];
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingMutableData:data];
- NSArray *array = @[@"one",@"two"];
- [archiver encodeInt:100 forKey:@"age"];//相当于SharedPreference的putInteger(key,value);
- [archiver encodeObject:array forKey:@"names"];//
- [archiver finishEncoding];//此方法调用,则将数据存入data
- [archiver release];
- if([data writeToFile:path atomically:YES]){
- NSLog(@"对象存入文件成功");
- }
2. 将数据从文件中取出
- NSData *data = [NSData dataWithContentOfFile:path];
- NSKeyedArchiver *unarchiver =[[NSKeyedArchiver alloc] initForReadingWithData:data];
- int age = [unarchiver decodeIntForKey:@"age"];//取出值
- NSArray *array = [unarchiver decodeObjectForKey:@"names"];
- [archiver release];
二. 使用NSUserDefaults类操作对象的存取
特点:该类将对象以键值对的形式存入系统固定的plist缓存文件,并通过key从文件中取出,与android中的SharedPreference应用场景一样,用于缓存小型简单的缓存数据
- //1. 存入数据
- NSArray *array = @[@"abc",@"d"];
- NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
- [userDefault setInteger:123 forKey:@"number"];
- [userDefault setObject:array forKey:@"array"];
- [userDefault synchronize];//存入文件
- //2. 取出数据
- NSInteger number = [userDefault integerForKey:@"number"];
- NSArray *array = [userDefault objectForKey:@"array"];