iOS 数据持久化三-NSUserDefaults

来源:互联网 发布:java 线程等待和唤醒 编辑:程序博客网 时间:2024/05/17 08:27

iOS中有五种持久化数据的方式:属性列表、对象归档、NSUserDefaults、SQLite3和Core Data

NSUserDefaults官方文档介绍:

NSUserDefaults类为和默认系统类交互提供了一种编程接口。默认系统允许应用程序去定制其行为,为了符合用户的喜好。举例来说,你可以允许用户去决定在应用程序中显示的计量单位或者文档多久会自动保存。应用程序在用户默认数据库中,通过给一系列参数赋值来记录类似的喜好。这些参数被称为默认值,因为它们通常被用于一个程序在启动时或默认状态下的默认工作状态。

在运行时,你可以使用NSUserDefaults对象读取你的应用程序的从一个用户默认数据库使用的默认数据。NSUerDefaults缓存信息,以避免每次获取一个默认值都需要打开用户默认的数据库。同步方法,他会每隔一段时间自动调用,使内存中缓存的信息与用户默认数据库中的信息同步。
NSUserDefaults
NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登录界面用户名、密码之类的,NSUserDefaults是比较合适。下次再登录的时候就可以直接从NSUserDefaults里面读取上次登录的信息,
[objc] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  AppDelegate.m  
  3. //  UserDefaultsDemo  
  4. //  
  5. //  Created by 李振杰 on 13-11-20.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10. #import "WelcomeViewController.h"  
  11. #import "RootViewController.h"  
  12.   
  13. @implementation AppDelegate  
  14.   
  15. - (void)dealloc  
  16. {  
  17.     [_window release];  
  18.     [super dealloc];  
  19. }  
  20.   
  21. - (void)isFirstLaunch  
  22. {  
  23.     //还未登录过  
  24.     if(![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]){  
  25.         //设置第二次使用的value值为yes  
  26.         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];  
  27.         //设置第一次使用的value值为yes  
  28.         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];  
  29.     }else{  
  30.         [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];  
  31.     }  
  32.       
  33.     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {  
  34.         WelcomeViewController *welcomeVC = [[WelcomeViewController alloc] init];  
  35.         [self.window setRootViewController:welcomeVC];  
  36.         [welcomeVC release];  
  37.     }else{  
  38.         RootViewController *rootVC = [[RootViewController alloc] init];  
  39.         [self.window setRootViewController:rootVC];  
  40.         [rootVC release];  
  41.     }  
  42. }  
  43.   
  44. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  45. {  
  46.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  47.     // Override point for customization after application launch.  
  48.       
  49.     [self isFirstLaunch];  
  50.     self.window.backgroundColor = [UIColor whiteColor];  
  51.     [self.window makeKeyAndVisible];  
  52.     return YES;  
  53. }  
  54.   
  55. @end  

NSUserDefaults类为访问普通类型的变量提供便利的方法,这些类型有floats,doubles,integers,booleans和URLs。一个默认的对象必须是一个属性列表,是NSData,NSString,NSNumber,NSDate,NSArray或者NSDictionary的实例。如果你想存储其它类型的对象,你应当将其转换成一个NSData的实例。

下面举例说明保存自定义对象Student到NSUserDefaults中,然后从NSUserDefaults中再读取出数据。

这里面包含了存取一个自定义对象和存取多个自定义对象这两种情况。
[objc] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  AppDelegate.m  
  3. //  UserDefaultsDemo  
  4. //  
  5. //  Created by 李振杰 on 13-11-20.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10. #import "WelcomeViewController.h"  
  11. #import "RootViewController.h"  
  12. #import "Student.h"  
  13.   
  14. @implementation AppDelegate  
  15.   
  16. - (void)dealloc  
  17. {  
  18.     [_window release];  
  19.     [super dealloc];  
  20. }  
  21.   
  22. - (void)isFirstLaunch  
  23. {  
  24.     //还未登录过  
  25.     if(![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]){  
  26.         //设置第二次使用的value值为yes  
  27.         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];  
  28.         //设置第一次使用的value值为yes  
  29.         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];  
  30.         Student *stu = [[Student alloc] init];  
  31.         NSLog(@"stu.name = %@\nstu.age = %d\nstu.height = %f\n", stu.name, [stu.age integerValue], [stu.height floatValue]);  
  32.   
  33.         [self saveCustomObjectToUerDefaults:stu];  
  34.         [stu release];  
  35.     }else{  
  36.         [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];  
  37.         [self saveManyStudentInfo];  
  38.     }  
  39.       
  40.     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {  
  41.         WelcomeViewController *welcomeVC = [[WelcomeViewController alloc] init];  
  42.         [self.window setRootViewController:welcomeVC];  
  43.         [welcomeVC release];  
  44.     }else{  
  45.         RootViewController *rootVC = [[RootViewController alloc] init];  
  46.         [self.window setRootViewController:rootVC];  
  47.         [rootVC release];  
  48.     }  
  49. }  
  50.   
  51. //保存多个自定义对象Student到NSUserDefaults中  
  52. - (void)saveManyStudentInfo  
  53. {  
  54.     NSMutableArray *stuArray = [[NSMutableArray alloc] init];  
  55.     for (int i = 0; i < 10; i++) {  
  56.         Student *stu = [[Student alloc] init];  
  57.         stu.name = [NSString stringWithFormat:@"Stu%d", i+1];  
  58.         stu.age = [NSNumber numberWithInteger:i+1];  
  59.         stu.height = [NSNumber numberWithFloat:170.3 + i];  
  60.         [stuArray addObject:stu];  
  61.         [stu release];  
  62.     }  
  63.     [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:stuArray] forKey:@"students"];  
  64. }  
  65.   
  66. //从nsuserDefaults加载多个自定义对象Student  
  67. - (NSArray *)loadManyStudentWithKey:(NSString *)key  
  68. {  
  69.       
  70.     NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"students"];  
  71.     NSArray *stuArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];  
  72.     return [stuArray retain];  
  73. }  
  74.   
  75. //保存自定义的对象到NSUserDefaults中  
  76. - (void)saveCustomObjectToUerDefaults:(Student *)student  
  77. {  
  78.     NSData *encodedCustomObject = [NSKeyedArchiver archivedDataWithRootObject:student];  
  79.     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  80.     [userDefaults setObject:encodedCustomObject forKey:@"student"];  
  81.     [userDefaults synchronize];  
  82. }  
  83.   
  84. //从NSuserDefaults中加载自定义的对象  
  85. - (Student *)loadCustomObjectWithKey:(NSString *)key  
  86. {  
  87.     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  88.     NSData *stuData = [userDefaults objectForKey:key];  
  89.     Student *student = [NSKeyedUnarchiver unarchiveObjectWithData:stuData];  
  90.       
  91.     return student;  
  92. }  
  93.   
  94. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  95. {  
  96.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  97.     // Override point for customization after application launch.  
  98.   
  99.     [self isFirstLaunch];  
  100.       
  101.     Student *stu = [self loadCustomObjectWithKey:@"student"];  
  102.     NSLog(@"stu.name = %@\nstu.age = %d\nstu.height = %f\n", stu.name, [stu.age integerValue], [stu.height floatValue]);  
  103.       
  104.     NSArray *arr = [self loadManyStudentWithKey:@"students"];  
  105.       
  106.     for (Student *student in arr) {  
  107.         NSLog(@"stu.name = %@\nstu.age = %d\nstu.height = %f\n", student.name, [student.age integerValue], [student.height floatValue]);  
  108.     }  
  109.       
  110.     self.window.backgroundColor = [UIColor whiteColor];  
  111.     [self.window makeKeyAndVisible];  
  112.     return YES;  
  113. }  
  114.   
  115. - (void)applicationWillResignActive:(UIApplication *)application  
  116. {  
  117.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
  118.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  119. }  
  120.   
  121. - (void)applicationDidEnterBackground:(UIApplication *)application  
  122. {  
  123.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.   
  124.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  125. }  
  126.   
  127. - (void)applicationWillEnterForeground:(UIApplication *)application  
  128. {  
  129.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  130. }  
  131.   
  132. - (void)applicationDidBecomeActive:(UIApplication *)application  
  133. {  
  134.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
  135. }  
  136.   
  137. - (void)applicationWillTerminate:(UIApplication *)application  
  138. {  
  139.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  140. }  
  141.   
  142. @end  



从NSUserDefaults返回的值都是不可变的。即使你设置了一个可变的值。例如,你设置了一个可变的字符串作为“MyStringDefault”的值,你用stringForKey:获取到的字符串将是不可变的。

默认数据库是为用户自动创建的。NSUserDefaults目前不支持per-host的偏好(设置)。要做到这一点,你必须使用CFPreferences API.然而,NSUserDefaults正确的读取per-host的偏好,所以你可以安全地混合CFPreferences与NSUserDefaults的代码。

如果你的应用程序支持管理的环境,你可以使用一个NSUserDefaults对象去决定哪些对用户有利的喜好是由管理员管理的。受管理的环境中对应的计算机实验室或教室管理员或教师肯能需要以一种特定的方式配置系统。在这种情况下,教师会建立一组默认的偏好设置并且强制对用户使用。如果以这种方式管理偏好设置,应用程序应该防止用户编辑,禁用任何适当的控制。

NSUserDefaults类是线程安全的。

NSURL的持久性和文件引用的URLs

当使用NSURL实例参考文件内的过程中,重要的是要基于位置的跟踪与文件系统的身份跟踪之间的区别。当坚持一个NSURL,你应该考虑采取这种行为。如果你的应用程序跟踪位于其身份的资源,那么当用户移动文件的时候你可以发觉到,那么你应该明确的解NSURL的书签数据或者对文件引用的URL进行编码。

如果你想通过文件的引用跟踪文件,但是当解析时你需要显式控制,你需要关心的把书签数据写到NSUserDefaults中,而不是依靠[NSUserDefaults setURL:forKey:],当你知道你的应用程序将能够处理潜在的I/O所需的用户界面交互时允许你调用[NSURL URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:]
沙盒注意事项
一个沙盒应用不能访问和修改其他应用的偏好设置。例如,如果你使用addSuiteNamed:方法添加另一个应用程序,但是你不会获得该应用程序的偏好设置。

尝试去访问或者修改另一个应用的偏好设置不会导致错误,但是当你你做的时候,世纪上OS X读取和写入位于应用程序容器内的文件,而不是其他应用程序的偏好设置文件。

这就是使用NsuserDefaults来是数据持久化的,你可以点击这里来下载NSUserDefaultsDemo
0 0