Learn to add CoreData in a project created

Source: Internet
Author: User

In the study CoreData, after the construction project, did not add, therefore the reference network article to make the change.

These days in learning to do an iOS small project, the project needs to make basic additions and deletions to the data operation. So I want to use a coredata. However, at the beginning of the project, no entry was included in CoreData. The CoreData is then added to the project that has been built. As a result of the first use of coredata, all aspects are not very familiar, crawling on the web, so that their own on the basis of this article after a day of research, special put their mistakes in a simple summary of the place. and refine the steps.

1. If you want to add CoreData to an already built project, you first need to introduce the CoreData FrameWork. You need to click Target First and then click Build Phases to find linkbinary with Libraries in the following interface. Click the arrow, expand this item, and then click the plus sign to see the framework item interface. Enter CoreData in the search box, then coredata.framework, select it and click the Add button to join the CoreData framework. The coredata.framework will appear below target. For easy classification of files, Coredata.framework can be dragged into the frameworks. And then save it just fine. Then add #import to the prefix.pch.


2. Add the data model, click the Iweather folder, then right-click, then click New File. Click iOS on the left side of the popup screen, select the CoreData below, then click on the data model on the right, then click Next to go to the next page, where the interface that pops up needs to be in Save as. Xcdatamodeld before writing the name of your data models. Here's the name of any write. I write here as iweather as the project name. Click Create, in Show the Project navigation creates a data model Iweather.xcdatamodeld.



3. After doing these tasks, don't rush to create an entity. But to delegate to build CoreData and delegate. At this point, click LWTAppDelegate.h, add the following code to @interface and @end;

@property (readonly,strong,nonatomic) Nsmanagedobjectcontext *managedobjectcontext;

@property (readonly,strong,nonatomic) Nsmanagedobjectmodel *managedobjectmodel;

@property (readonly,strong,nonatomic) Nspersistentstorecoordinator *persistentstorecoordinator;

-(void) savecontext;

-(Nsurl *) applicationdocumentsdirectory;

The above code has several name terms: Nsmanagedobjectcontext,nsmanagedobjectmodel,nspersistentstorecoordinator.

(1). Managed Object Model (Management data Model): You can look at this thing as a database outline, or structure. This contains the definition information for each entity, in general, you will use the visual editor we have just seen to manipulate the object, add attributes, establish relationships between attributes, and of course you can use the code.

(2). Persistent Store Coordinator (persistent data Coordinator): You can consider this as a database connection library, where you will set the name and location of the data store, and the timing of the data storage.

(3). Managed Object Context (Managing Data content): You can think of this part as the actual content of the data, which is the most important part of the whole database for us (which is to say), basically, the work of inserting data, querying data, and deleting data is done here.

The above-mentioned explanation of the term is excerpted from: http://www.dasheyin.com/ios_jiao_cheng_core_data_shu_ju_chi_jiu_xing_cun_chu_ji_chu_jiao_cheng.html .

4. After opening the LWTAPPDELEGATE.M file, write the following code under @implementation:

@synthesize Managedobjectcontext =_managedobjectcontext;

@synthesize Managedobjectmodel = _managedobjectmodel;

@synthesize persistentstorecoordinator = _persistentstorecoordinator;

Then add the following code before @end:

Equivalent to the method of saving data

-(void) Savecontext

{

Nserror *error = nil;

Nsmanagedobjectcontext *managedobjectcontext =self.managedobjectcontext;

if (Managedobjectcontext!=nil) {

if ([Managedobjectcontexthaschanges] &&![ Managedobjectcontextsave:&error]) {

NSLog (@ "Unresolvederror%@,%@", error, [Erroruserinfo]);

Abort ();

}

}

}

#pragma mark-core Data Stack

Returns the managed object context for the application.

If the context doesn ' t already exist, it's created and bound to Thepersistent store coordinator for the application.

-(Nsmanagedobjectcontext *) Managedobjectcontext

{

if (_managedobjectcontext!=nil) {

return _managedobjectcontext;

}

Nspersistentstorecoordinator *coordinator = [Selfpersistentstorecoordinator];

if (Coordinator! = nil) {

_managedobjectcontext = [[Nsmanagedobjectcontextalloc]init];

[_managedobjectcontextsetpersistentstorecoordinator:coordinator];

}

return _managedobjectcontext;

}

Returns the managed object model for the application.

If the model doesn ' t already exist, it's created from the application ' Smodel.

-(Nsmanagedobjectmodel *) Managedobjectmodel

{

if (_managedobjectmodel!=nil) {

return _managedobjectmodel;

}

It is important to note here that the Iweather is the name of the data model you have just created, and must be consistent. Otherwise you will get an error.

Nsurl *modelurl = [[nsbundlemainbundle]urlforresource:@ "Iweather" withextension:@ "MOMD"];

_managedobjectmodel = [[Nsmanagedobjectmodelalloc]initwithcontentsofurl:modelurl];

return _managedobjectmodel;

}

Returns the persistent store coordinator for the application.

If the coordinator doesn ' t already exist, it's created and theapplication ' s store added to it.

-(Nspersistentstorecoordinator *) persistentstorecoordinator

{

if (_persistentstorecoordinator!=nil) {

return _persistentstorecoordinator;

}

The iweaher.sqlite here should also be consistent with the name of the data model.

Nsurl *storeurl = [[selfapplicationdocumentsdirectory]urlbyappendingpathcomponent:@ "IWeather.sqlite"];

Nserror *error = nil;

_persistentstorecoordinator = [[nspersistentstorecoordinatoralloc]initwithmanagedobjectmodel:[ Selfmanagedobjectmodel]];

if (![ _persistentstorecoordinatoraddpersistentstorewithtype:nssqlitestoretypeconfiguration:nilurl:storeurloptions: Nilerror:&error]) {

NSLog (@ "Unresolvederror%@,%@", error, [Erroruserinfo]);

Abort ();

}

return _persistentstorecoordinator;

}

#pragma mark-application ' s Documents directory

Returns the URL to the application ' s Documents directory.

-(nsurl*) applicationdocumentsdirectory

{

Return[[[nsfilemanagerdefaultmanager]urlsfordirectory:nsdocumentdirectoryindomains:nsuserdomainmask]lastobject ];

}

All the preparations have been done here. Then go to create entity.

5. Open the Iweather.xcdatamodeld file. Switch to view mode by using the Editor style button. Like this:


Then click the Add Entity button to add the entity.

Then we modify the entity. Click on the entity to change that to Arinfo. Then click the AddAttribute button to add the properties. Add both the myID and MyName properties. The property type is string.


After doing this, start building the corresponding. h and. m files. Right click on the Iweather folder, click NewFile, select Nsmanagedobject Subclass in the pop-up window, then click on the Next button will appear the Select Entity window (not necessarily, may not appear, if not appear, It depends on the creation of the new file is associated with that entity, if the entity is more, should appear, do not appear on the establishment of an entity of an entity, and then click Next to select the Save interface, save both. The two files will appear in the project ArInfo.h and ARINFO.M.


6. Then join the @interface and @end in LWTAViewController.h

@property (strong,nonatomic) Nsmanagedobjectcontext *context;

Add @synthesize context after @implementation in LWTAVIEWCONTROLLER.M;

and add in LWTAVIEWCONTROLLER.M

#import "ArInfo.h"

#import "LWTAppDelegate.h"

These two header files. Then add the following code to the Viewdidload:

Lwtappdelegate *delegate = (lwtappdelegate *) [[UIApplication sharedapplication]delegate];//there is a need to introduce a delegate to your project, is to make the global managedobjectcontext work.

Self.context = Delegate.managedobjectcontext;

Arinfo *arinfo = [nsentitydescriptioninsertnewobjectforentityforname:@ "Arinfo" inmanagedobjectcontext:context];

[Email protected] "123";

[Email protected] "object-c";

Nserror *error = nil;

if (![ Contextsave:&error]) {

NSLog (@ "%@", [errorlocalizeddescription]);

}

Nsfetchrequest *fetchrequest = [[Nsfetchrequestalloc]init];

Nsentitydescription *entity = [nsentitydescriptionentityforname:@ "Arinfo" inmanagedobjectcontext:context];

[Fetchrequest setentity:entity];

Nsarray *fetchobject = [contextexecutefetchrequest:fetchrequesterror:&error];

For (Nsmanagedobject *infoin fetchobject) {

NSLog (@ "id:%@", [infovalueforkey:@ "myID"]);

NSLog (@ "name:%@", [infovalueforkey:@ "myname"]);

}

Run the program at this point. The all output outputs:

Id:123

Name:object-c

Learn to add CoreData in a project created

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.