Question

I have a UIViewController for user to input their data and submit to our ASP.NET Webapi. there are about 40 textField and other controls.

Is there any way i can save the input locally. the data will not be clear until user click the submit button. I want the data still there even restart the phone or restart the program. save in XML ?

Was it helpful?

Solution

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).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top