NSUserDefaults

NSUserDefaults

//get instance
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//set
[defaults setObject:@"valueOfString" forKey:@"keyOfString"]; 
[defaults synchronize]; //一般来说,setObject 之后,NSUserDefaults会自动保存数据到plist文件,这里作此操作,防止程序意外退出,未保存设置
//get
NSString *settingValue = [defaults objectForKey:@"keyOfString"];
NSLog(settingValue);
支持的Key类型
  • NSString
支持的Value类型
  • NSString
  • NSArray
  • NSDictionary
  • NSDate
  • NSNumber
  • NSData (当数据类型不在支持范围内时,可转为此类型存储)
注册&重置默认值

//register default value
NSDictionary *defaultSettings = @{
       @"language": @"chs",
       @"maxdownnum": @"3"
};
[defaults registerDefaults:defaultSettings];œ
//restore default value
NSDictionary *settingDict = [defaults dictionaryRepresentation]; // 返回的dictionary中包含许多非本应用的设置项,注意排除
for(NSString *key in settingDict)
{
   [defaults removeObjectForKey:key];
}

一些常用存取方法

//get

- (NSString *)stringForKey:(NSString *)defaultName;
- (NSArray *)arrayForKey:(NSString *)defaultName;
- (NSDictionary *)dictionaryForKey:(NSString *)defaultName;
- (NSData *)dataForKey:(NSString *)defaultName;
- (NSArray *)stringArrayForKey:(NSString *)defaultName;
- (NSInteger)integerForKey:(NSString *)defaultName;
- (float)floatForKey:(NSString *)defaultName;
- (double)doubleForKey:(NSString *)defaultName;
- (BOOL)boolForKey:(NSString *)defaultName;
- (NSURL *)URLForKey:(NSString *)defaultName;
//set
- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;
- (void)setFloat:(float)value forKey:(NSString *)defaultName;
- (void)setDouble:(double)value forKey:(NSString *)defaultName;
- (void)setBool:(BOOL)value forKey:(NSString *)defaultName;
- (void)setURL:(NSURL *)url forKey:(NSString *)defaultName ;

在文件中添加设置项

添加工程模板文件:Setting Bundle -->修改文件:root.plist

在代码中修改root的设置同上

posted @ 2015-07-10 17:28  denjuy  阅读(153)  评论(0编辑  收藏  举报