Data storage and retrieval in ios Sebastian Ernst, PhD! Department of Applied Computer Science AGH University of Science and Technology
File structure of an ios app ios apps can store they data in files. These files are typically placed in the app s Documents folder. That folder is persistent between app launches and is deleted when the app is uninstalled. The NSSearchPathForDirectoriesInDomains foundation function can be used to find the location of the Documents folder: dirpaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
File structure of an ios app The first result will contain the path to the folder. docsdir = dirpaths[0]; The full name can be easily concatenated: NSString *datafilepath = [NSString stringwithstring:[docsdir stringbyappendingpathcomponent: @"universities.archive"]];
Archiving Objects can be easily serialized (and deserialized) thanks to the NSKeyedArchiver and NSKeyedUnarchiver objects. [NSKeyedArchiver archiverootobject:self.unidb tofile:datafilepath];! self.unidb = [NSKeyedUnarchiver unarchiveobjectwithfile:datafilepath]; Supported data types: NSArray, NSData, NSDate, NSDictionary, NSNumber and NSString.
SQLite ios contains built-in support for SQLite. However, since SQLite support functions are in plain C, one needs to rememeber about converting proper data types (NSString to const char *, NSNumber to int, etc.). To add SQLite support to an app: link with the libsqlite3.dylib library, include sqlite3.h where appropriate.
Core Data Because of the drawbacks (pure C implementation, requirement to know SQL), ios also includes a higher-level data persistence API called Core Data. The default storage engine still SQLite, but other solutions (incl. XML and binary serialization) can also be used.
Core Data: structure source: techotopia.com
Core Data: elements Managed Objects are what the app actually interacts with. They are instances of the NSManagedObjects class or its children. The Managed Object Context is where the Managed Objects live. The context maps the objects to their counterparts in the permanent store. It acts as a buffer and persists changes only when instructed to do so.
Core Data: elements, cont d. The Managed Object Model is where the structure of data is defined. Xcode includes a GUI to manage the MOM. The model is based on entities and their attributes. Entities are linked using relationships. Fetched Properties are also used to link entities. The docs describe them as weak, one way relationships best suited to loosely coupled relationships The Persistent Store Coordinator and Persistent Object Store are low-level parts of the storage engine.
Core Data: getting the context The context can be obtained from the application delegate: coredataappdelegate *appdelegate = [[UIApplication sharedapplication]! delegate];! NSManagedObjectContext *context = [appdelegate managedobjectcontext];
Creating entity descriptions Entity descriptions are used to manipulate objects. They can be obtained using the NSEntityDescription class. NSEntityDescription *entitydesc = [NSEntityDescription! entityforname:@"contacts"! inmanagedobjectcontext:context];! NSFetchRequest *request = [[NSFetchRequest alloc] init];! [request setentity:entitydesc];
Creating managed objects NSEntityDescription also has a method to create managed objects: NSManagedObject *newcontact;! newcontact = [NSEntityDescription! insertnewobjectforentityforname:@"contacts"! inmanagedobjectcontext:context];! NSError *error;! [context save:&error];
Setting attribute values Of course, the new object still does not have attribute values. They need to be set: [newcontact setvalue:@ John Smith forkey:@"name"];! [newcontact setvalue:@ 123 The Street! forkey:@"address"];! [newcontact setvalue:@ 555-123-1234! forkey:@"phone"];
Getting attribute values Attribute values can be retrieved in a similar manner: NSString *contactname =! [newcontact valueforkey:@ name ];
Fetching objects Objects are retrieved using the fetch operation. NSFetchRequest *request = [[NSFetchRequest alloc] init];! [request setentity:entitydesc];! NSError *error;! NSArray *matching_objects =! [context executefetchrequest:request error:&error];
Fetching using criteria To fetch only objects matching certain criteria, one can use predicates, already presented in an early lecture: NSFetchRequest *request = [[NSFetchRequest alloc] init];!! [request setentity:entitydesc];! NSPredicate *pred = [NSPredicate! predicatewithformat:@"(name = %@)", John Smith ];! [request setpredicate:pred];! NSError *error;! NSArray *matching_objects = [context executefetchrequest:request error:&error]; ;
More on Core Data An ios 7 Core Data Tutorial
Getting data from the server The easiest method to get data from the server is by using RESTful APIs. The built-in methods use ansynchronous calls to retrieve data using HTTP. The connection is set up like so: NSURL *myurl = [NSURL URLWithString:@"http://www.flickr.com/ services/rest/?method=flickr.test.echo&format=json &api_key=8038f7f7d7151ccbf6df2aa10b1b35ae&nojsoncallback=1"]; NSURLRequest *myrequest = [NSURLRequest requestwithurl:myurl]; NSURLConnection *myconnection = [NSURLConnection connectionwithrequest:myrequest delegate:self]; More information: TechRepublic, ios Web Service Tutorial, https:// developer.apple.com/library/ios/documentation/cocoa/conceptual/ URLLoadingSystem/Tasks/UsingNSURLConnection.html