iOS數據存取和對象序列化 – iPhone手機開發技術文章 iPhone軟體開發教學課程

一. 使用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"];

發佈留言