Data persistence in iOS 1-coredata

Source: Internet
Author: User

CodeData is a relational database provided by Apple. Below are some of the other bloggers ' summaries (forget the copy link at the time of the copy):

Managed Objects (managed object): a Managed object represents an object that you want to save to the data store
managed Object Contexts (Managed object context): a Managed object context is similar to a buffer between an application and a data store. This buffer contains all managed objects that have not been written to the data store. You can add, delete, and change managed objects within a buffer. In many cases, when you need to read, insert, and delete objects, you will invoke the methods of the managed object context.
Persistent Storage Coordinator (persistent store coordinator): The persistent storage Coordinator handles the connection to the data store and contains some underlying information, such as the name and location of the data store. This class is typically used by the managed object context.
managed Object Model: The Managed object model is a class that contains the definitions of every managed object that you want to store in the data store (managed).

Using CoreData

1. Before you can read or write model objects to the current data store, you need to instantiate the managed object model, the managed object context, and the persisted storage coordinator. the managed object model is represented by an instance of the Nsmanagedobjectmodel class. In a project we only need to instantiate an object for all of the. xcdatamodeld files. nsmanagedobjectmodel* Managedobjectmodel = [NsmanagedobjectmodelMergedmodelfrombundles:nil];mergedmodelfrombundles: Search all the. xcdatamodeld files in the project and load all the entities into one Nsmanagedobjectmodel instance. This allows the managed object model to know the definition of all managed objects used in the current project

2 with the managed object Model instance, we can create a persistence coordinator instance. The persistence coordinator processes the connection to the data store. It's probably dealing with how to write objects to the data store or how to read objects from the data store.

3 with the Persistence Coordinator instance, we need to provide a data store to manage it. You can do this by sending a addPersistentStoreWithType:configuration:URL:options:error: message.

4 The final step is to instantiate the managed object context. With the managed object context, you can easily manage objects.  How to get the managed object context in Appdelegat, the persistence Coordinator, the managed object model: here are the personal experiences when using:

Summarize:

Nsmanagedobjectmodel: Instantiating a managed object is already in use in appdeletage and does not directly manipulate the object in order to create the persisted storage coordinator Persistentstorecoordinator, when it is actually used:
Persistentstorecoordinator: To create a link to a data store, the object is not used directly in the actual operation
Therefore, the managed object context is used in actual use


To add a data procedure:
1. Create Entity Data Description Nsentitydescription
2. Create an instance object from a profile
3. Save

When the program is created, the CoreData appdelegate automatically creates the following three properties for us

@synthesize managedobjectcontext = _managedobjectcontext;

@synthesize Managedobjectmodel = _managedobjectmodel;

@synthesize persistentstorecoordinator = _persistentstorecoordinator;

and automatically implemented the following four methods for us:

- (void) savecontext{Nserror*error =Nil; Nsmanagedobjectcontext*managedobjectcontext =Self.managedobjectcontext; if(Managedobjectcontext! =Nil) {        if([Managedobjectcontext haschanges] &&! [Managedobjectcontext save:&ERROR]) {             //Replace This implementation with code to handle the error appropriately. //Abort () causes the application to generate a crash log and terminate. You should don't use the This function in a shipping application, although it could be useful during. NSLog (@"unresolved error%@,%@", error, [error userInfo]);        Abort (); }     }}#pragmaMark-core Data Stack//Returns the managed object context for the application.//If The context doesn ' t already exist, it's created and bound to the persistent store coordinator for the application .-(Nsmanagedobjectcontext *) managedobjectcontext{if(_managedobjectcontext! =Nil) {        return_managedobjectcontext; } nspersistentstorecoordinator*coordinator =[self persistentstorecoordinator]; if(Coordinator! =Nil) {_managedobjectcontext=[[Nsmanagedobjectcontext alloc] init];    [_managedobjectcontext Setpersistentstorecoordinator:coordinator]; }    return_managedobjectcontext;}//Returns the managed object model for the application.//If The model doesn ' t already exist, it is created from the application ' s model.-(Nsmanagedobjectmodel *) managedobjectmodel{if(_managedobjectmodel! =Nil) {        return_managedobjectmodel; } Nsurl*modelurl = [[NSBundle mainbundle] Urlforresource:@"Core_data"Withextension:@"MOMD"]; _managedobjectmodel=[[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; return_managedobjectmodel;}//Returns The persistent store coordinator for the application.//If The Coordinator doesn ' t already exist, it's created and the application ' s store added to it.-(Nspersistentstorecoordinator *) persistentstorecoordinator{if(_persistentstorecoordinator! =Nil) {        return_persistentstorecoordinator; } Nsurl*storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@"Core_data.sqlite"]; Nserror*error =Nil; _persistentstorecoordinator=[[Nspersistentstorecoordinator alloc] initwithmanagedobjectmodel:[self Managedobjectmodel]]; if(! [_persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype Configuration:nil URL:storeURL options:@ {nsmigratepersistentstoresautomaticallyoption: @YES, nsinfermappingmodelautomaticallyoption: @YES} error:&ERROR]) {        /*         Replace This implementation with code to handle the error appropriately. Abort () causes the application to generate a crash log and terminate.                   You should don't use the This function in a shipping application, although it could be useful during.         Typical reasons for a error here include: * The persistent store was not accessible;         * The schema for the persistent store was incompatible with current managed object model.                           Check the error message to determine what the actual problem is. If the persistent store is not accessible, there are typically something wrong with the file path.                  Often, a file URL is pointing into the application ' s resources directory instead of a writeable directory. If you encounter the schema incompatibility errors during development, you can reduce the their frequency by: * Simply Deleting the existing store: [[Nsfilemanager Defaultmanager] RemoveiTematurl:storeurl Error:nil] * Performing automatic lightweight migration by passing the following Dictio Nary as the options parameter: @{nsmigratepersistentstoresautomaticallyoption: @YES, nsinfermappingmodelautomatical Lyoption: @YES} Lightweight migration would only work for a limited set of schema changes;                   Consult "Core Data Model Versioning and Data Migration Programming Guide" for details.*/NSLog (@"unresolved error%@,%@", error, [error userInfo]);    Abort (); }            return_persistentstorecoordinator;}#pragmaMark-application ' s Documents directory//Returns the URL to the application ' s Documents directory.-(Nsurl *) applicationdocumentsdirectory{return[[[ Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask] lastObject];}

Data persistence in iOS 1-coredata

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.