Core Data persistent data storage (3)-write core data code

Source: Internet
Author: User
Tags prototype definition

Write core dataCode

During the previous data model creation process, we have created three managed objects (nsmanagedobject), that is, object objects.

Here, we create objects in other data core frameworks and enable the persistent storage of core data.
Open the cartappdelegate. h file in the project and add the nsmanagedobjectcontext attribute and the prototype definition of the two methods. The updated code is as follows:

# Import <uikit/uikit. h>

@ Interface cartappdelegate: uiresponder
@ Property (strong, nonatomic) uiwindow * window;

@ Property (strong, nonatomic) nsmanagedobjectcontext * managedobjectcontext;
-(Void) insertdata=shoppingcartdb;
-(Void) displayshoppingcart;

@ End

Open the cartappdelegate. M file and add the @ synthesize compilation command for the managedobjectcontext attribute.
@ Synthesize managedobjectcontext = _ managedobjectcontext;

Further implement the initialization method of managedobjectcontext instance variables. This code is a bit difficult to understand. The following explains how to first obtain the storage location of the storage file (or database file). Here it is set to the document directory of the app, and the storage file (or database file) is shoppingcar database.
Then, create the nspersistentstorecoordinator object and specify the storage type (SQLite database) and storage path. Finally, instantiate the managed object context and assign the value to its persistent Storage Coordinator.
-(Nsmanagedobjectcontext *) managedobjectcontext {
If (_ managedobjectcontext = nil ){
Nsurl * url = [[nsfilemanager defaultmanager] urlsfordirectory: nsdocumentdirectory
Indomains: nsuserdomainmask] lastobject];
Nsurl * storedatabaseurl = [url urlbyappendingpathcomponent: @ "shoppingcart. SQLite"];
// Set the SQLite database storage path/shoppingcart. SQLite
Nserror * error = nil;

// Create an nspersistentstorecoordinator object instance based on the managed Object Model
Nspersistentstorecoordinator * persistentstorecoordinator =
[[Nspersistentstorecoordinator alloc]
Initwithmanagedobjectmodel: [nsmanagedobjectmodel mergedmodelfrombundles: Nil];

// Create a New persistent store based on the specified storage type and Path)
If (! [Persistentstorecoordinator addpersistentstorewithtype: nssqlitestoretype
Configuration: Nil
URL: storedatabaseurl options: Nil error: & error])
{
Nslog (@ "error while loading persistent store... % @", error );
}

_ Managedobjectcontext = [[nsmanagedobjectcontext alloc] init];

// Set the persistent Storage Coordinator for the context of the currently managed object
[_ Managedobjectcontext setpersistentstorecoordinator: persistentstorecoordinator];
}

// Return the initialized context instance of the managed object
Return _ managedobjectcontext;
}

 

The insertdata‑shoppingcartdb method defined in the Implementation interface of the cartappdelegate. M file is mainly used to insert some initial data into the SQLite database for testing purposes.
The following code inserts initialization data into three entities: customer, shoppingcartmaster, and shoppingcartdetail.
// Insert some initial data into SQLite
-(Void) insertdata=shoppingcartdb {
// Create a customer managed object instance
Customer * customer1 = (customer *) [nsentitydescription insertnewobjectforentityforname: @ "customer"
Inmanagedobjectcontext: Self. managedobjectcontext];
Customer1.customerid = [nsnumber numberwithint: 1];
Customer1.customername = @ "customer name-stupid ";
Customer1.password = @ "entlib.com ";
Customer1.username = @ "entlib.com ";

// Create a shoppingcartmaster managed object instance
Shoppingcartmaster * shoppingcartmaster1 = (shoppingcartmaster *) [nsentitydescription
Insertnewobjectforentityforname: @ "shoppingcartmaster" inmanagedobjectcontext: Self. managedobjectcontext];
Shoppingcartmaster1.cartid = [nsnumber numberwithint: 100];
Shoppingcartmaster1.customerid = [nsnumber numberwithint: 1];

// Create a shoppingcartdetail managed object instance
Shoppingcartdetail * shoppingcartdetail1 = (shoppingcartdetail *) [nsentitydescription
Insertnewobjectforentityforname: @ "shoppingcartdetail" inmanagedobjectcontext: Self. managedobjectcontext];
Shoppingcartdetail1.cartid = [nsnumber numberwithint: 100];
Shoppingcartdetail1.currentprice = [nsdecimalnumber decimalnumberwithdecimal:
[[Nsnumber numberwithfloat: 18.5f] decimalvalue];

Shoppingcartdetail1.productid = @ "1-111-111 ";
Shoppingcartdetail1.productname = @ "Hello Kitty-iPhone 5 ";
Shoppingcartdetail1.productsysno = [nsnumber numberwithint: 10];

Shoppingcartdetail * shoppingcartdetail2 = (shoppingcartdetail *) [nsentitydescription
Insertnewobjectforentityforname: @ "shoppingcartdetail" inmanagedobjectcontext: Self. managedobjectcontext];
Shoppingcartdetail2.cartid = [nsnumber numberwithint: 100];
Shoppingcartdetail2.currentprice = [nsdecimalnumber decimalnumberwithdecimal:
[[Nsnumber numberwithfloat: 18.5f] decimalvalue];

Shoppingcartdetail2.productid = @ "2-222-111 ";
Shoppingcartdetail2.productname = @ "Hello Kitty-iPad 3 Tablet ";
Shoppingcartdetail2.productsysno = [nsnumber numberwithint: 10];

// Assign a value to the instance variable of the link property.
// During development and testing, you can comment out the following code and analyze and compare it.
Customer1.cart = shoppingcartmaster1;
[Shoppingcartmaster1 adddetailobject: shoppingcartdetail1];
[Shoppingcartmaster1 adddetailobject: shoppingcartdetail2];

// Save data and persistently store the SQLite Database
// During development and testing, you can comment out the following code and analyze and compare it.
/* If ([self. managedobjectcontext haschanges]) {
[Self. managedobjectcontext save: Nil];
}*/

}

Note: In the above Code, we commented out the save operation for writing data to the SQLite database. This is just to avoid repeated insertion of initial data into the database during the test process. If you remove the preceding Code annotations, you can store data in the SQLite database.

Continue to implement the displayshoppingcart method defined in the interface in the cartappdelegate. M file. This method is used to output object data in the context of the managed object in xcode debugging window.
// Display the content in the SQLite database and shopping cart
-(Void) displayshoppingcart {
// The nsfetchrequest object is used to retrieve data.
Nsfetchrequest * request = [[nsfetchrequest alloc] init];

// Create an nsentitydescription object based on the specified entity name and the context of the managed object,
Nsentitydescription * myentityquery = [nsentitydescription
Entityforname: @ "customer"
Inmanagedobjectcontext: Self. managedobjectcontext];
// Specify the object
[Request setentity: myentityquery];

Nserror * error = nil;
// Returns an array of records that meet the query condition nsfetchrequest.
Nsarray * customerarr = [self. managedobjectcontext executefetchrequest: Request error: & error];
Nsinteger recordcount = [mermerarr count];
Nslog (@ "record count: % d", recordcount );
For (INT I = 0; I <recordcount; I ++ ){
// The element in the array is the customer managed object.
Customer * customer = (customer *) [customerarr objectatindex: I];
Nslog (@ "customername: % @", customer. customername );

// Obtain the shoppingcartmaster object corresponding to the customer. One-to-one relationship
Shoppingcartmaster * cart = Customer. cart;
Nslog (@ "my shopping cart: % @", cart. cartid );

// Obtain an array of all detail objects in the shoppingcartmaster object, one-to-multiple relationship
Nsarray * productlist = [Cart. Detail allobjects];
Int numberofproducts = [productlist count];
Nslog (@ "Number of cart items: % d", numberofproducts );

 

// Traverse the shoppingcartdetail Array
For (INT I = 0; I <numberofproducts; I ++ ){
Shoppingcartdetail * detail = [productlist objectatindex: I];
Nslog (@ "Shopping Cart item: % @", detail. productname );
}
}
}

Note: here we use the managed object context to obtain data, that is, to obtain data in the memory. Therefore, the [self. managedobjectcontext save: Nil] The code line can return results even if it is commented.

Finally, we need to modify the application: didfinishlaunchingwitexceptions: code in the method in the cartappdelegate. M file. The updated code is as follows, mainly to add the call to the two methods we defined earlier.
-(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions
{
// Override point for customization after application launch.
[Self insertdata=shoppingcartdb];
[Self displayshoppingcart];

 

Return yes;
}

As for application: didfinishlaunchingwitexceptions: When will the method be called?
Here, we need to briefly introduce the iOS appProgram.

IOS application Lifecycle

When we create an application, the main. M file is automatically created in the project's supporting Files folder.

Main. m is the entry of the program. Let's take a look at the code of the Main. M file.

# Import <uikit/uikit. h>
# Import "cartappdelegate. H"

 

Int main (INT argc, char * argv [])
{
@ Autoreleasepool {
Return uiapplicationmain (argc, argv, nil, nsstringfromclass ([cartappdelegate class]);
}
}

Execute a method uiapplicationmain in Main. This method returns a uiapplicationmain object that represents our application object.
The fourth parameter is a string, which is the cartappdelegate class of the application delegate. This is also automatically created by xcode during project creation.
The previously modified application: didfinishlaunchingwitexceptions: method is in this class. This method is always called when the IOS program starts.

--

Not finished yet !!!

the content and examples of this tutorial are included in the latest PDF file step by step iOS 6 programming ..

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.