The use of CoreData in iOS

Source: Internet
Author: User

This article reprinted to http://m.blog.csdn.net/blog/chen505358119/9334831

Core data persistence is an upgrade to SQLite, it's iOS integrated, and before we say core data, let's talk about several classes used in CoreData.

(1) Nsmanagedobjectmodel (managed object model)

Equivalent to an entity, but it contains relationships between entities

(2) Nsmanagedobjectcontext (Managed Object context)

Manipulating the actual content

Role: Insert Data query Update delete

(3) Nspersistentstorecoordinator (persistent storage assistant)

A connector equivalent to a database

(4) Nsfetchrequest (Request to get data)

Equivalent to a query statement

(5) Nspredicate (equivalent to query criteria)

(6) Nsentitydescription (solid structure)

(7) A package with a suffix named. Xcdatamodel

The. xcdatamodel file inside, edited with the Data Model Editor

Compiled for. MOMD or. Mom files, which is why there is no such thing in the file, and our program uses this thing without error.

First, we're going to build the model object

Next we want to generate the entity user for the model object, which is inherited by the Nsmanagedobjectmodel

After clicking, you will find that it will automatically generate the user, and now it is mainly said that the generated user object is this form of

This explains the dynamic. We're in contact with synthesize.

What is the difference between dynamic and synthesize? Its setter and getter methods are defined

Open the CoreData SQL statement output switch

1. Open product, click Editscheme ...
2. Click arguments to add 2 items to argumentspassed on launch
1>-com.apple.coredata.sqldebug
2> 1

#import <UIKit/UIKit.h> #import <CoreData/CoreData.h> @class viewcontroller; @interface appdelegate: Uiresponder <UIApplicationDelegate> @property (Strong, nonatomic) UIWindow *window; @property (Strong, Nonatomic) Viewcontroller *viewcontroller; @property (strong,nonatomic,readonly) nsmanagedobjectmodel* managedObjectModel;@ Property (strong,nonatomic,readonly) nsmanagedobjectcontext* managedobjectcontext; @property (Strong,nonatomic, readonly) nspersistentstorecoordinator* Persistentstorecoordinator; @end

#import "AppDelegate.h" #import "ViewController.h" @implementation appdelegate@synthesize managedobjectmodel=_ Managedobjectmodel, @synthesize managedobjectcontext=_managedobjectcontext, @synthesize persistentstorecoordinator    =_persistentstorecoordinator;-(void) dealloc{[_window release];    [_viewcontroller release];    [_managedobjectcontext release];    [_managedobjectmodel release];    [_persistentstorecoordinator release]; [Super Dealloc];}    -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions{    Self.window = [[[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]] autorelease];    Override point for customization after application launch.    Self.viewcontroller = [[[Viewcontroller alloc] initwithnibname:@ "Viewcontroller" Bundle:nil] autorelease];    Self.window.rootViewController = Self.viewcontroller;    [Self.window makekeyandvisible]; return YES;} -(void) Applicationwillresignactive: (uiapplication *) application{//Sent when the application is on-move from active to inactive state. This can occur for certain types of temporary interruptions (such as a incoming phone call or SMS message) or when the US    Er quits the application and it begins the transition to the background state. Use the This method to the pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should with this method to pause the game.} -(void) Applicationdidenterbackground: (uiapplication *) application{//Use the method to release shared resources, SAV E user data, invalidate timers, and store enough application state information to restore your application     State-in-case it is terminated later. If your application supports background execution, this method is called instead of Applicationwillterminate:when the User quits.} -(void) Applicationwillenterforeground: (uiapplication *) application{//called as part of the transition from the BACKG Round to the inactive State Here's can undo many of the changes made on entering the background.} -(void) Applicationdidbecomeactive: (uiapplication *) application{//Restart Any tasks this were paused (or not yet star Ted) While the application was inactive. If the application is previously in the background, optionally refresh the user interface.} -(void) Applicationwillterminate: (uiapplication *) application{//Called when the application was about to terminate. Save data if appropriate. See also Applicationdidenterbackground:.}    Managed Object-(Nsmanagedobjectmodel *) managedobjectmodel{if (_managedobjectmodel!=nil) {return _managedobjectmodel; }//nsurl* modelurl=[[nsbundle Mainbundle] urlforresource:@ "coredataexample" withextension:@ "MOMD"];//_managedObj    Ectmodel=[[nsmanagedobjectmodel alloc] Initwithcontentsofurl:modelurl];    _managedobjectmodel=[[nsmanagedobjectmodel Mergedmodelfrombundles:nil] retain]; return _managedobjectmodel;} Managed Object Context-(Nsmanagedobjectcontext *) managedobjectcontext{if (_managedobjectcontext!=nil) {return _managedobjectcontext;    } nspersistentstorecoordinator* coordinator=[self Persistentstorecoordinator]; if (coordinator!=nil) {_managedobjectcontext=[[nsmanagedobjectcontext alloc] Initwithconcurrencytype:nsmainqueueco                Ncurrencytype];    [_managedobjectcontext Setpersistentstorecoordinator:coordinator]; } return _managedobjectcontext;} Persistent Storage Coordinator-(Nspersistentstorecoordinator *) persistentstorecoordinator{if (_persistentstorecoordinator!=nil) {R    Eturn _persistentstorecoordinator; }//nsurl* storeurl=[[self applicationdocumentsdirectory] urlbyappendingpathcomponent:@ "CoreaDataExample.CDBStore" ];//nsfilemanager* Filemanager=[nsfilemanager defaultmanager];//if (![ FileManager Fileexistsatpath:[storeurl Path])//{//nsurl* defaultstoreurl=[[nsbundle Mainbundle] URLForResourc         e:@ "Coredataexample" withextension:@ "Cdbstore"];//if (defaultstoreurl) {//   [FileManager copyitematurl:defaultstoreurl tourl:storeurl error:null];//}//} nsstring* docs=[NSSearchPat    Hfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject];    nsurl* storeurl=[nsurl fileurlwithpath:[docs stringbyappendingpathcomponent:@ "Coredataexample.sqlite"];    NSLog (@ "path is%@", storeurl);    nserror* Error=nil; _persistentstorecoordinator=[[nspersistentstorecoordinator Alloc] Initwithmanagedobjectmodel:[self    Managedobjectmodel]]; if (![ _persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL options:    Nil Error:&error]) {NSLog (@ "error:%@,%@", Error,[error UserInfo]); } return _persistentstorecoordinator;} -(Nsurl *) applicationdocumentsdirectory//{//return [[[Nsfilemanager Defaultmanager] Urlsfordirectory: NSDocumentDirectory Indomains:nsuserdomainmask] lastobject];//} @end

#import <UIKit/UIKit.h> #import "AppDelegate.h" @interface Viewcontroller:uiviewcontroller@property (Retain, nonatomic) Iboutlet Uitextfield *nametext; @property (retain, nonatomic) Iboutlet Uitextfield *agetext; @property (retain , nonatomic) Iboutlet Uitextfield *sextext; @property (nonatomic,retain) appdelegate* myappdelegate;-(IBAction) Addintodatasource: (ID) sender;-(ibaction) query: (ID) sender;-(ibaction) Update: (ID) sender;-(ibaction) del: (ID) Sender

#import "ViewController.h" #import "User.h" @interface Viewcontroller () @end @implementation viewcontroller-(void)    viewdidload{[Super viewdidload];//do no additional setup after loading the view, typically from a nib. _myappdelegate= (Appdelegate *) [[uiapplication sharedapplication] delegate];}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.}    -(void) Dealloc {[_nametext release];    [_agetext release];    [_sextext release]; [Super Dealloc];} Insert Data-(ibaction) Addintodatasource: (ID) Sender {user* user= (User *) [nsentitydescription    insertnewobjectforentityforname:@ "User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];    [User Setname:_nametext.text];    [User Setage:[nsnumber Numberwithinteger:[_agetext.text IntegerValue]];    [User Setsex:_sextext.text];    nserror* error;    BOOL Issavesuccess=[_myappdelegate.managedobjectcontext save:&error]; if (!issavesuccess) {NSLog (@ "error:%@", Error); }else{NSLog (@ "Save successful!");}}    Query – (ibaction) query: (ID) Sender {nsfetchrequest* request=[[nsfetchrequest alloc] init]; nsentitydescription* user=[nsentitydescription entityforname:@ "user" inmanagedobjectcontext:_    Myappdelegate.managedobjectcontext]; [Request setentity:user];//nssortdescriptor* Sortdescriptor=[[nssortdescriptor alloc] initwithkey:@ "name" ascending : yes];//nsarray* Sortdescriptions=[[nsarray alloc] initwithobjects:sortdescriptor, nil];//[Request SetSortDescript    ors:sortdescriptions];//[Sortdescriptions release];//[Sortdescriptor release];    nserror* Error=nil; nsmutablearray* Mutablefetchresult=[[_myappdelegate.managedobjectcontext executefetchrequest:request error:&    ERROR] mutablecopy];    if (Mutablefetchresult==nil) {NSLog (@ "error:%@", Error);    } NSLog (@ "The Count of entry:%i", [Mutablefetchresult Count]); For (user* User in Mutablefetchresult) {NSLog (@ "name:%@----age:%@------sex:%@ ", user.name,user.age,user.sex);    } [Mutablefetchresult release]; [Request release];}    Update-(ibaction) Update: (ID) Sender {nsfetchrequest* request=[[nsfetchrequest alloc] init]; nsentitydescription* user=[nsentitydescription entityforname:@ "user" inmanagedobjectcontext:_    Myappdelegate.managedobjectcontext];    [Request Setentity:user];    Query conditions nspredicate* predicate=[nspredicate predicatewithformat:@ "name==%@", @ "Chen"];    [Request Setpredicate:predicate];    nserror* Error=nil; nsmutablearray* Mutablefetchresult=[[_myappdelegate.managedobjectcontext executefetchrequest:request error:&    ERROR] mutablecopy];    if (Mutablefetchresult==nil) {NSLog (@ "error:%@", Error);    } NSLog (@ "The Count of entry:%i", [Mutablefetchresult Count]);            Save after update age, otherwise no update for (user* user in Mutablefetchresult) {[user setage:[nsnumber numberwithint:12]];    } [_myappdelegate.managedobjectcontext save:&error]; [MutablefetchresultRelease];    [Request release];    }//Delete-(ibaction) del: (ID) Sender {nsfetchrequest* request=[[nsfetchrequest alloc] init]; nsentitydescription* user=[nsentitydescription entityforname:@ "user" inmanagedobjectcontext:_    Myappdelegate.managedobjectcontext];    [Request Setentity:user];    nspredicate* predicate=[nspredicate predicatewithformat:@ "name==%@", @ "Chen"];    [Request Setpredicate:predicate];    nserror* Error=nil; nsmutablearray* Mutablefetchresult=[[_myappdelegate.managedobjectcontext executefetchrequest:request error:&    ERROR] mutablecopy];    if (Mutablefetchresult==nil) {NSLog (@ "error:%@", Error);    } NSLog (@ "The Count of entry:%i", [Mutablefetchresult Count]);    For (user* User in Mutablefetchresult) {[_myappdelegate.managedobjectcontext deleteobject:user];     } if ([_myappdelegate.managedobjectcontext Save:&error]) {NSLog (@ "error:%@,%@", Error,[error UserInfo]); }} @end

Use of CoreData in iOS

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.