有关NSUserDefaults(资料整理)

作者:暗夜星辰 发布于:2013-3-7 11:09 Thursday 分类:IOS学习笔记

之前么有用过NSUserDefaults,大体了解概念,整理下,把它搞明白。

NSUserDefaults 是iPhone 提供的数据持久化的方法的一种,这样的话,就是说可以用NSUserDefaults来保存部分数据,不必使用数据库。

- (void)applicationDidFinishLaunching:(UIApplication *)application {
 NSString *strOne = @"Persistent data1";
 NSString *strTwo = @"Persistent data 2";

 NSMutableArray *persistentArray = [[NSMutableArray alloc] init];
 [persistentArray addObject:strOne];
 [persistentArray addObject:strTwo];

 //archive
 NSUserDefaults *persistentDefaults = [NSUserDefaults standardUserDefaults];
 [persistentDefaults setObject:persistentArray forKey:@"myDefault"];
 NSString *descriptionDefault = [persistentDefaults description];
 NSLog(@"NSUserDefaults description is :%@",descriptionDefault);

 //unarchive
 NSArray *UnpersistentArray =

[persistentDefaults objectForKey:@"myDefault"];


 NSString *UnstrOne = [UnpersistentArray objectAtIndex:0];
 NSString *UnstrTwo = [UnpersistentArray objectAtIndex:1];

 NSLog(@"UnstrOne = %@,UnstrTwo = %@",UnstrOne,UnstrTwo);

 // Override point for customization after application launch
 [window makeKeyAndVisible];
}

NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary. 如果把一个自定义的类存到一个NSArray里,然后再存到NSUserDefaults里也是不能成功的。

NSUserDefaults可以用来注册程序的出厂设置,保存用户偏好设置,以及读取之前保存过得用户偏好设置

举个例子

If you have an application that should save for example state of a switch and you don’t want use database for that small request you can simply add instance of NSUserDefaults class in your implementation. It is easy job, see below;

- (IBAction) saveState {

NSString *value = @"ON";
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
if(!switch.on){
value = @"OFF";
[userPreferences setObject:value forKey:@"stateOfSwitch"];
}
[userPreferences setObject:value forKey:@"stateOfSwitch"];

}

This is part of code that loads value in a NSString *value for key stateOfSwitch. When you start your application again and view finisheds with loading button will be in lefted state.

- (void)viewWillAppear:(BOOL)animated {

NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:@"stateOfSwitch"];

if([_value compare:@"ON"] == NSOrderedSame){
switch.on = YES;
}
else {
switch.on = NO;
}
[super viewWillAppear:animated];
}

标签: IOS xcode obj-c

发表评论:

©2012-2014 woodbunny.com 木头♥兔子的小屋 sitemap