能够将可变数据类型存入,可是取出来的时候,数据类型会变成不可变shell
自定义数据类型, 例如自定义模型, 须要先转成 NSData
类型才能存储数据库
nil
//存
[[NSUserDefaults standardUserDefaults] setObject:value forKey:@"key"];
复制代码
//取
id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"key"];
复制代码
//强制同步数据
[[NSUserDefaults standardUserDefaults] synchronize];
复制代码
关于 NSUserDefaults
, 官方文档有这么一段话:缓存
At runtime, you use NSUserDefaults objects to read the defaults that your app uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.app
NSUserDefaults 会将访问到的 key 和 value 缓存到内存中, 下次访问时, 若是缓存中命中这个 key, 就直接访问, 若是没有命中, 再从文件中载入, 会时不时调用 synchronize
来保证数据的一致性, 可是这个操做非实时的, 为了防止数据丢失, 咱们应该在对重要的数据保存时使用synchornize
方法强制写入, 但也不要过于频繁, 毕竟频繁访问数据库影响性能async
// 沙盒下
AppData/Library/Preferences/Bundle\ Identifier.plist
复制代码
官方注释:性能
adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them. Default values from Defaults Configuration Files will automatically be registered.ui
大体是说, 当应用内没有这个值时, 这个值将做为默认值存在, 若是这个 key 已经存在, 那么这个值将做为备用, 而且当 app 再次启动, 这个默认值并不会替换已经存在的值, 咱们用几行代码来讲明spa
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys: @"blue", @"color", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
return YES;
}
复制代码
[[NSUserDefaults standardUserDefaults] setObject:@"red" forKey:@"color"];
复制代码
这时 NSUserDefaults 里 @"color" = @"red"code
registerDefaults
仍是会被调用, 但它会查到 @"color" key 已存在, 并不会把 @"blue" 写进去registerDefaults
修改成NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys: @"black", @"color",@"tomson", @"username",nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
复制代码
这时, NSUserDefaults 内 @"color" 依然为 @"red", 但多了 @"username" = @"tomson"orm
从性能上分析, 缓存的机制带来了必定的性能提高, 经过一些网上的文章了解到在10万个key的状况下, 经过NSUserDefaults
来读取value是1ms级别的, 然而当你从plist文件中直接读取, 须要100ms的级别开销, 可是写是个相反的结果, 要是你写1个10万条数据到plist文件中是1s级别的开销,而同时写入10万条NSUserDefaults
键值对则须要10s级别的延迟. 咱们都知道在建立key/value时, 程序须要在内存中也建立一个相应的映射关系, 而后系统会时不时调用synchronsize
方法同步数据, 不少的方法会致使建立key/value pair被阻塞
总的来讲, 使用NSUserDefaults
是比较高效的, 可是不能大量的将数据经过 NSUserDefaults 中