IOS Data Persistence CoreData

Source: Internet
Author: User


This article is about the http://www.cnblogs.com/kenshincui/p/4077833.html#autoid-3-1-0 finishing


CoreData is a data persistence solution introduced after iOS3.0, an object-relational mapping (ORM), such as hibernate in the Java background, the ORM framework in iOS first CoreData, which is officially recommended without the need for a third-party framework, is actually a package for SQLite that provides a more advanced persistence method that does not require the use of SQL statements in database operations, or the ability to manipulate databases directly

The purpose of the ORM Framework is to transform the tables (entities) in a relational database into objects in a program, essentially manipulating the database, coredata the mapping of object relationships.

Using CoreData for database access does not need to create a database manually, this process is completely coredata framework, developers face the model, the main task is to create the model, the specific database how to create and no tube,

CoreData compared with SQLite, sqlite relatively primitive, operation is more complex, using the function of C to the database operation, but CoreData can not cross the platform, SQLite can cross the platform, more controllable, more lightweight.


Below is a simple study of the use of CoreData:


1. Select User CoreData when creating the project





2. The following objects and methods are automatically generated in Appdelegate





The role of each of these objects: (Nsmanagerobjectcontext more important)

    • Persistent Object Store: a database that can be understood to store persistent objects (such as sqlite, note that core data also supports other types of data storage, such as XML, binary data, and so on).
    • Managed Object Model: A model file that corresponds to the models created in Xcode.
    • Persistent Store Coordinator: the conversion coordinator between the object model and the entity class for managing the context of different storage objects.
    • Managed Object Context: Objects management context, which is responsible for interaction between the entity object and the database.

3. Create entity models and relationships:



Note In the process of model creation:

    • The entity object does not need to create an ID primary key, and attributes should be a meaningful attribute (the properties of the object should be taken into account in the creation process rather than the table in the database, although most properties correspond to the table's fields).
    • All properties should specify a specific type (although not specified in SQLite), because the entity object will generate the OBJC model class accordingly.
    • The properties of other entity object types in the entity object should be established through relationships and be aware of the correspondence between entities (for example, one user has multiple tweets, while a microblog belongs to only one user, and the user and Weibo form a two-to-many relationship).

4. Generate a specific entity class based on the model file (. xcdatamodeld file) above .



Each entity class system automatically generates 4 files User.h, USER.M (User's coredataproperties Class)




It is important to note the following points:

    • All entity types inherit from Nsmanagedobject, and each Nsmanagedobject object corresponds to a record in the database.
    • Collection properties, such as status in user, generate a classification method that accesses this property.
    • Using @dynamic to represent the implementation of a specific property, the implementation details do not require the developer's concern.
5. Create a good entity and relationship, you can do the operation of the data to be increased and censored:

CoreData The operation is mainly based on nsmanagerobjectcontext, create the context, save the data

Here you can use the Nsmanagerobjectcontext object provided by Appdelegate

Add data: Call Nsentitydescription to return an entity object, and then set the object's properties, save the context (when performing the redaction operation, be sure to invoke the Save method of the admin context, otherwise the operation will not execute)

<span style= "FONT-SIZE:18PX;" >//Add Data-(ibaction) add: (ID) Sender {    //Create entity object with Nsentitydescription    User *user = [nsentitydescription insertnewobjectforentityforname:@ "User" inManagedObjectContext:self.managerObjectContext];    User.Name = @ "Xia";    User.age = @ "+";    User.time = [NSDate datewithtimeintervalsincenow:0];    Nserror *error;    Save Context    if (![ Self.managerobjectcontext Save:&error]) {        NSLog (@ "error message during the Add process---%@", error.localizeddescription);}    } </span>

query data: Implemented by predicates, first creates a request, sets the requested predicate, invokes the context execution

Note: The following related to Nspredicate expansion

<span style= "FONT-SIZE:18PX;" >//Query data-(ibaction) Equery: (ID) Sender {    //query GET request, set query which entity entityname    nsfetchrequest *request = [ Nsfetchrequest fetchrequestwithentityname:@ "User"];    Nsfetchrequest has a property predicate predicate (nspredicate type)    //A query condition similar to a query statement   used to query        //query user table name is xia user    Request.predicate = [nspredicate predicatewithformat:@ "name= ' Xia '"];        You can also use the following query statement format//    NSString *name = @ "Xia";//    request.predicate = [nspredicate predicatewithformat:@ "name Like [CD]%@ ", name];    Nsarray *array = [Self.managerobjectcontext executefetchrequest:request error:nil];} </span>

Delete Data

<span style= "FONT-SIZE:18PX;" >//Delete data-(ibaction) Delete: (ID) Sender {        //Get all the data in the table first    nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@ "User"];    Nsarray *array = [Self.managerobjectcontext executefetchrequest:request error:nil];        The array of table data is traversed for the    (User *user in array) {        //condition Delete        if ([User.Name isequaltostring:@ "Xia"]) {            [ Self.managerobjectcontext Deleteobject:user];        }            }        Nserror *error;    Save Context    if (![ Self.managerobjectcontext Save:&error]) {        NSLog (@ "error message occurred during deletion-----%@", error.localizeddescription);}    } </span>

Update Data

<span style= "FONT-SIZE:18PX;" >//Update Data-(ibaction) Update: (ID) Sender {    //Get an entity first    User *user = [self getuserbyusername:@ "Xia"];        Modify the properties of an entity    User.Name = @ "Yan";    User.age = @ "+";        Nserror *error;    Save Context    if (![ Self.managerobjectcontext Save:&error]) {        NSLog (@ "Update data error error message----%@", error.localizeddescription);    }} Get the user entity class via username-(user *) Getuserbyusername: (NSString *) username{    //user *user = [[User alloc] init];    Nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@ "User"];    Nsarray *array = [Self.managerobjectcontext executefetchrequest:request error:nil];    For (User *auser in array) {        if ([Auser.name isequaltostring:username]) {            return auser;               }    }    return nil;} </span>

about the expansion of Nspreidicate nspredicate for querying and filtering
In SQL, where is usually used as a query condition, but nspredicate can be used as a query condition in CoreData.
Nspredicate can not only be used in conjunction with the Fetchrequest in CoreData. can also be used in conjunction with the Nsarray.
Keywords and conditional characters supported in Nspredicate:

1, >,<,>=,<=,= comparison operator.
Such as:

Nspredicate * qcondition= [nspredicate predicatewithformat:@ "salary >= 10000"];

2. String manipulation (Included): Beginswith, ENDSWITH, CONTAINS
Such as:

@ "Employee.Name beginswith[cd] ' li '"//employee surnamed Li

@ "Employee.Name endswith[c] ' dream '"//employee with Dream end

@ "Employee.Name contains[d] ' zong '"//Employees with "Zong" word

Note: [c] case insensitive [d] does not distinguish between pronounced symbols and no accent marks [CD] are neither case sensitive nor pronounced.



3. Range: In, Bwteen
Such as:

@ "Salary Bwteen {5000,10000}"

@ "em_dept in ' development '"



4, itself: Self, this only works for character arrays.
Such as:

Nsarray * test = =[nsarray arraywithobjects: @ "Guangzhou", @ "Beijing", @ "Shanghai", nil];

@ "self= ' Beijing '"



5. Wildcard characters: like
Like use? represents a character, * represents more than one character, or can be used with C, D.

Such as:

@ "Car.name like '? He? '"//four characters, middle is he

@ "Car.name like ' *jp '"//End with JP


6. Regular expression: MATCHES
Such as:

NSString *regex = @ "^e.+e$";//The character that begins with E and ends with E.
Nspredicate *pre= [nspredicate predicatewithformat:@ "Self MATCHES%@", regex];
if ([Pre evaluatewithobject: @ "Employee"]) {
NSLog (@ "matches YES");

}else{
NSLog (@ "matches NO");

}

7. Logical operators: And, or, not Such as:

@ "Employee.Name = ' john ' and employee.age = 28"

8. Placeholder: nspredicate *pretemplate = [nspredicate predicatewithformat:@ "name== $NAME"];
Nsdictionary *dic=[nsdictionary Dictionarywithobjectsandkeys:
@ "Name1", @ "NAME", nil];
Nspredicate *pre=[pretemplate Predicatewithsubstitutionvariables:dic];
The placeholder is the key in the Dictionary object, so you can have multiple placeholders, as long as the key is different.



CoreData operations are converted to SQL operations, setting up support for CoreData debugging on Xcode

Add two parameters in Product-scheme-edit scheme-run-arguments (note the order of the parameters can not be wrong ):-com.apple.coredata.sqldebug ,1. Then, when you run the program, if you manipulate the database, the SQL statements are printed in the output panel




Last Note: CoreData thread safety issues and CoreData version migration issues, next time to organize




IOS Data Persistence 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.