# iOSDataStorage

We know that there are many storage solutions in iOS programming. Today I’d like to introduce some of them.

# Preferences

If you like to store some preferences and settings, which is normally very light-weight, I think the best way to do that is to use NSUserDefaults.

## Explaination

In the code block above, we can conclude that the first thing we need to do is initialize an userDefault. And we can handle with many types of data like Bool, Integer, Object and etc using setForKey and ForKey to set and get data. It’s very easy to understand.

Moreover, if you like to synchronize immediately, please call [userDefaults synchronize];

# Plist

First, you need to learn something about iOS document path.

Of course, there are some differences among different paths, you can google it.

## Path

1. mainBundle Path

2. document Path

3. library Path

4. preference Path

5. temp Path

## Sample Code

### Explaination

In the code block above, we can conclude that we need to firstly give a specified name of the file and then use that file to call [NSArray arrayWithContentsOfFile:fileName] and [dict writeToFile:fileName atomically:YES](dict is an initialization).

# NSKeyedArchiver

## Sample Code

Firstly, I have a class named Person like:

Then we can use this class to make sense of NSKeyedArchiver.

## Explaination

If you like to use NSKeyedArchiver to read or write, you must have a model which follows the protocal <NSCoding> and implement the initWithCoder and encodeWithCoder functions.

Then, an initialization of that class could be written or read using [NSKeyedArchiver archiveRootObject:person toFile:file] and [NSKeyedUnarchiver unarchiveObjectWithFile:file].

# SQLite3

## Prerequisite

To use SQLite, you need firstly add the framework libsqlite3.tbd into your project’s Link Binary With Libraries in Build Phases.

## Explaination

Firstly you need a sqlite3 item to use the database.

# Core Data

Core Data, in some degree, is the most complicated but important solution on iOS platform. It provides us the ORM function and change an OC item into Data or something on the contrary.

## Prerequisite

To use Core Data, you must create Core Data Data Model by pressing command + n and selecting Data Model.

Next, you need to edit the .ecdatamodeld file to add you entry and models.

Then, add mapping files.(Editor-Create NSManagedObject Subclass)

Now you are able to use the core data model.

## Sample Code

I have such model and mapping files:

And here is the sample source code:

## Explaination

Remember: one db, one context.