Lecture #12: Persistence

Please note, this blog entry is from a previous course. You might want to check out the current one.

Lecture twelve is named “12. Persistence (November 3, 2011)” and can be found at iTunes. Its slides are available at Stanford.

The first part of this lecture is designated to guidelines of the final project of the course and because it is targeted at campus students has been omitted from the iTunes stream.

The second part is devoted to persistence – the ways to save data between launchings of an application.

Besides NSUserDefaults for small amounts of data, iOS provides several other methods:

  • property lists,
  • archiving,
  • filesystem,
  • SQLite and
  • Core Data.

Property lists provide additional methods to store to (writeToURL:atomically:) and and load from (initWithContentsOfURL:) local or remote URLs. In addition NSPropertyListSerialization can be used to convert them to NSData streams.

Archiving is a mechanism which allows to make any object persistent (contrary to the previously described methods which work only with certain object types) by implementing the NSCoding protocol:

- (void)encodeWithCoder:(NSCoder *)coder;
- initWithCoder:(NSCoder *)coder;

The actual storage and retrieval is done to NSData objects:

+ (NSData *)archivedDataWithRootObject:(id <NSCoder>)rootObject; NSKeyedUnarchiver retrieves an 
+ (id <NSCoder>)unarchiveObjectWithData:(NSData *)data;

The file system in iOS works like a normal Unix file system. It allows write processes only inside the sandbox of the application to provide security and privacy as well as a simple way for cleanup. Thus if it is necessary to write to file which has been provided in the original application bundle, it must be copied into a writable location to be writable.

The NSFileManager provides access to the files as well as utility operations.

SQLite is bundled in iOS and provides SQL functionality where the whole database is stored in a single file:

// to open the database:
int sqlite3_open(const char *filename, sqlite3 **db); 
// to execute SQL statements:
int sqlite3_exec(sqlite3 *db, const char *sql,
                 int (*callback)(void *, int, char **, char **),
                 void *context, char **error);
// to access the returned data:
int mycallback(void *context, int count, char **values, char **cols);
// to close the database:
int sqlite3_close(sqlite3 *db);
FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.