Store data locally IOS

故事扮演 提交于 2019-11-30 23:02:55

There are quite a few options that you could choose from, ranging in complexity as follows:

  • Use an NSKeyedArchiver to save to the local filesystem. This involves making your model class conform to the NSCoding protocol.

  • Use sqlite and a local database. The C api can be quite verbose, however there is a nice Objective-C wrapper called FMDB.

  • Use CoreData. This involves creating a local data-model (object schema) and then instructing CoreData to persist the object to its storage. Storage is typically an sqlite database (includes ACID compliance - eg transactions, atomicity, etc), but CoreData also knows how to do binary and XML formats.

Whichever approach you use, I recommend using the Data Access Object (DAO) design pattern, which provides a protocol for persistence methods. Examples:

- (Customer*) findCustomByLastName:(NSString*)lastName
- (void) save:(Customer*)customer

. . in this way its possible to start with a very simple style of persistence, to test how your overall architecture integrates into a cohesive app, and then swap in another more robust style later. Here's an example of a file-system DAO using NSKeyedArchiver.

Other approaches:

  • The ActiveRecord pattern is an alternative to Data Access Object, and there are some very popular and well-supported libraries that provide this with CoreData. Use the ActiveRecord pattern or the DAO pattern, but probably you should avoid just dumping all of the persistence code in your view controller! ;)
  • Nick Lockwood created a nice utility to make working with NSKeyedArchiving easy.
  • For simple cases you could also use NSUserDefaults
  • If security is required, you could save to the keychain. Again the API is somewhat low-level, however there are nice wrappers. Here's one.
  • Since the NeXTSTEP days, an NSDictionary has provided methods to serialize itself to disk in various formats. Modern formats include XML, JSON, binary. (And there are some funky legacy formats, that can still be read, but are deprecated for writing. . such as the one Xcode uses to save its project.pbxproj file).

You can either store the data in NSUserDefaults or in a SQLite database. I'd recommend SQLite but it totally depends on your need. There's loads of tutorials on how to do this on YouTube/apple dev docs

Check out Realm

A mobile database that runs directly inside phones, tablets or wearables. Realm lets you build apps faster, build apps that are faster, and craft previously impossible experiences.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!