在日常开发中经常要对NSString、NSDictionary、NSArray、NSData、NSNumber这些基本类的数据进行持久化,我们可以用XML属性列表持久化到.plist 文件中,也可以用NSUserDefaults,下面我们就开搞吧。
XML属性列表方式:
#import "AppDelegate.h"
#import "Person.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSDictionary *studentDic = [NSDictionary dictionaryWithObjectsAndKeys:@"SuperDo.Mount",@"student_mount",@"SuperDo.AC",@"student_ac",@"SuperDo.Horse",@"student_horse", nil]; //获得Document的路径
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documents stringByAppendingPathComponent:@"students.plist"]; //保存到Document目录下
if([studentDic writeToFile:path atomically:YES]) {
NSLog(@"Save to file success!");
} //从path初始化
NSDictionary *students = [NSDictionary dictionaryWithContentsOfFile:path];
for (NSString *key in students.allKeys) {
NSLog(@"%@: %@",key,[students objectForKey:key]);
} return YES;
} @end
保存到Documet下文件信息:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>student_ac</key>
<string>SuperDo.AC</string>
<key>student_horse</key>
<string>SuperDo.Horse</string>
<key>student_mount</key>
<string>SuperDo.Mount</string>
</dict>
</plist>
NSUserDefaults 方式:
#import "AppDelegate.h"
#import "Person.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSDictionary *studentDic = [NSDictionary dictionaryWithObjectsAndKeys:@"SuperDo.Mount",@"student_mount",@"SuperDo.AC",@"student_ac",@"SuperDo.Horse",@"student_horse", nil]; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:studentDic forKey:@"students"]; NSDictionary *dic = [userDefaults objectForKey:@"students"];
for (NSString *key in dic.allKeys) {
NSLog(@"NSUserDefaults 方式 ---- 》 %@: %@",key,[dic objectForKey:key]);
} return YES;
} @end
XML属性列表方式打印结果:
2015-07-06 20:39:53.623 Attendance[1129:68434] Save to file success!
2015-07-06 20:39:53.624 Attendance[1129:68434] student_ac: SuperDo.AC
2015-07-06 20:39:53.624 Attendance[1129:68434] student_mount: SuperDo.Mount
2015-07-06 20:39:53.624 Attendance[1129:68434] student_horse: SuperDo.Horse
NSUserDefault方式打印结果:
2015-07-06 20:50:44.743 Attendance[1155:70007] NSUserDefaults 方式 ---- 》 student_mount: SuperDo.Mount
2015-07-06 20:50:44.743 Attendance[1155:70007] NSUserDefaults 方式 ---- 》 student_ac: SuperDo.AC
2015-07-06 20:50:44.743 Attendance[1155:70007] NSUserDefaults 方式 ---- 》 student_horse: SuperDo.Horse
本站文章为宝宝巴士 SD.Team原创,转载务必在明显处注明:(作者官方网站:宝宝巴士)
转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4625366.html