美文网首页
iOS开发之NSUserDefaults学习和使用

iOS开发之NSUserDefaults学习和使用

作者: LuckyBugGo | 来源:发表于2018-10-26 15:37 被阅读0次

1. NSUserDefaults是什么

先怼官方定义:

An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.
The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user’s preferences.

NSUserDefaults官方文档链接
综上,可以简单理解NSUserDefaults为:

  1. 它是一个本地存储的数据库,专门存放应用的默认设置数据。
  2. 它使用键值对存储数据,而且建议只存储轻量级别的用户配置数据。

2. 什么情况适合使用NSUserDefaults

当应用需要存储一些轻量级的数据时,可以使用NSUserDefaults来完成。比如:

  1. 应用的主题配置:日间模式或者夜间模式等。
  2. 应用的用户信息:使用于需要登录型的应用,可将数据量不是那么多的用户资料存放到NSUserDefaults中去。
    其实主要是一些轻量级别的应用数据都可以用NSUserDefaults来进行存储,至于怎样去衡量数据量,很大程度上还是依赖开发者。

3. 怎么使用NSUserDefaults

3.1 获取系统默认的实例对象

NSUserDefaults *userDefaults =  [NSUserDefaults standardUserDefaults];

standardUserDefaults方法会返回一个全局的实例对象,一般情况下,使用这个实例对象就可以了。
当一个应用可能会有登录多个用户,而且应用都要保持这些用户的数据时。那么仅仅一个userDefaults的数据可能就不够了,就要创建多个userDefaults来存储了(在实际开发中,这种情况下的用户数据不就建议使用userDefaults来存储了,苹果官方现在也不建议这么做。当然部分开发者为了展示自己高超的开发技巧,会强行使用userDefaults来存储)。那么以下方法可以 帮你创建多个UserDefaults。

-initWithSuiteName: initializes an instance of NSUserDefaults that searches the shared preferences search list for the domain 'suitename'. For example, using the identifier of an application group will cause the receiver to search the preferences for that group. Passing the current application's bundle identifier, NSGlobalDomain, or the corresponding CFPreferences constants is an error. Passing nil will search the default search list.

- (nullable instancetype)initWithSuiteName:(nullable NSString *)suitename

3.2 存储数据

// 存储对象类型,比如:字符串、字典或者数组等
- (void)setObject:(nullable id)value forKey:(NSString *)defaultName;
// 存储整型数据
- (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;
// 存储URL数据
- (void)setURL:(nullable NSURL *)url forKey:(NSString *)defaultName

3.3 读取数据

// 读取对象
- (nullable id)objectForKey:(NSString *)defaultName;
// 读取字符串
- (nullable NSString *)stringForKey:(NSString *)defaultName;
// 读取数组
- (nullable NSArray *)arrayForKey:(NSString *)defaultName;
// 读取字典
- (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)defaultName;
// 读取data数据
- (nullable NSData *)dataForKey:(NSString *)defaultName;
// 读取整型数据
- (NSInteger)integerForKey:(NSString *)defaultName;
// 读取浮点型数据
- (float)floatForKey:(NSString *)defaultName;
// 读取双精度数据
- (double)doubleForKey:(NSString *)defaultName;
// 读取布尔数据
- (BOOL)boolForKey:(NSString *)defaultName;
// 读取URL
- (nullable NSURL *)URLForKey:(NSString *)defaultName

相关文章

网友评论

      本文标题:iOS开发之NSUserDefaults学习和使用

      本文链接:https://www.haomeiwen.com/subject/prwftqtx.html