NSUserDefaults的一些使用心得

· NSUserDefaults

平时开发中使用 NSUserDefaults 来进行一些简单配置数据的保存是很方便的。大家也都知道 NSUserDefaults`其实是对一个plist文件的读写,那么问题来了,如果一个很大很复杂的应用,使用了各种SDK,且各个业务模块独立开发,大家都要用NSUserDefaults来保存一些设置,除了各自需要保证自己设置key的唯一性外,plist文件越来越大所带来的读写效率问题也不同忽视。

· initWithSuiteName

原本想自己写一个NSUserDefaults类似的工具来保存的配置信息到单独的plist文件,发现NSUserDefaults 有一个初始化方法:

/// -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 NS_AVAILABLE(10_9, 7_0) NS_DESIGNATED_INITIALIZER;

使用此方法初始化NSUserDefaults会以suitename为文件名创建独立的plist文件(默认是以应用的bundle id为文件名的)。这样就可以创建单独的plist文件进行读写了。

-initWithSuiteName原本是在APP Group中用来进行应用间数据共享的,suitenameCapabilities 中设置的 App Groups 的id匹配的情况下,该plist文件会被创建到设备的共享目录 AppGroup 中,否则则会创建到应用沙盒 Library > Preferences 目录下。

你可能感兴趣的:(NSUserDefaults的一些使用心得)