Core Data uses

Source: Internet
Author: User

Note: Each time you modify the CoreData attribute remember to apply to remove the reload, to not collapse, because the database file is still in the directory, the field is not changed, so can not match will crash, avoid, or every time you come in to remove the file first, and then build, However, it seems that the user's data will be lost, so or every time you remove the app reload it.

1. First set up a CoreData project and use Core data to hook up

The following code is included in the APPDELEGATE.M:

#pragmaMark-core Data Stack@synthesizeManagedobjectcontext =_managedobjectcontext;@synthesizeManagedobjectmodel =_managedobjectmodel;@synthesizePersistentstorecoordinator =_persistentstorecoordinator;
The exact location stored in the sandbox
-(Nsurl *) Applicationdocumentsdirectory {//The directory the application uses to store the Core Data store file. This code uses a directory named "Com.pupuwang.XWClient.CoreDataDemo" in the application ' s documents directory. return[[[ Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask] lastObject];}
Managed Objects-(Nsmanagedobjectmodel *) Managedobjectmodel {//The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. if(_managedobjectmodel! =Nil) { return_managedobjectmodel; } Nsurl*modelurl = [[NSBundle mainbundle] Urlforresource:@"Coredatademo"Withextension:@"MOMD"]; _managedobjectmodel=[[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; return_managedobjectmodel;}
Persistent Storage Coordinator-(Nspersistentstorecoordinator *) Persistentstorecoordinator {//The persistent store coordinator for the application. This implementation creates and return a coordinator, has added the store for the application to it. if(_persistentstorecoordinator! =Nil) { return_persistentstorecoordinator; } //Create the coordinator and store_persistentstorecoordinator=[[Nspersistentstorecoordinator alloc] initwithmanagedobjectmodel:[self Managedobjectmodel]]; Nsurl*storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@"Coredatademo.sqlite"]; Nserror*error =Nil; NSString*failurereason =@"there is an error creating or loading the application ' s saved data."; if(! [_persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL options: Nil error:&ERROR]) { //Report any error we got.Nsmutabledictionary *dict =[Nsmutabledictionary dictionary]; Dict[nslocalizeddescriptionkey]=@"Failed to initialize the application ' s saved data"; Dict[nslocalizedfailurereasonerrorkey]=Failurereason; Dict[nsunderlyingerrorkey]=error; Error= [Nserror Errorwithdomain:@"Your_error_domain"Code9999Userinfo:dict]; //Replace this 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 (); } return_persistentstorecoordinator;} Managed context-(Nsmanagedobjectcontext *) Managedobjectcontext {//Returns the managed object context for the application (which are already bound to the persistent store Coordinator fo R the application.) if(_managedobjectcontext! =Nil) { return_managedobjectcontext; } nspersistentstorecoordinator*coordinator =[self persistentstorecoordinator]; if(!coordinator) { returnNil; } _managedobjectcontext=[[Nsmanagedobjectcontext alloc] init]; [_managedobjectcontext Setpersistentstorecoordinator:coordinator]; return_managedobjectcontext;}#pragmaMark-core Data Saving support-(void) Savecontext {nsmanagedobjectcontext*managedobjectcontext =Self.managedobjectcontext; if(Managedobjectcontext! =Nil) {Nserror*error =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 (); } }}

Manually set up CoreData files yourself, or you can write them manually

2. Establishing entities

With the Xcdatamodeld suffix file selected, proceed as follows:

Select the Xcdatamodeld suffix file, click the navigation bar editor->create Nsmanagedobject subclass all the way next, build the model object User.h USER.M

The properties inside the generated model:user are @dynamic

@property have two corresponding words, one is @synthesize and the other is @dynamic. If @synthesize and @dynamic are not written, then the default is @syntheszie var = _var;

The semantics of @synthesize is that if you do not implement setter methods and Getter methods manually, then the compiler will automatically add these two methods to you.

@dynamic tells the compiler that the setter and getter methods of the property are implemented by the user themselves and are not generated automatically. (Of course, for ReadOnly properties, only getter is required). If a property is declared as @dynamic var, then you do not provide the @setter method and the @getter method, the compile time is not a problem, but when the program runs to Instance.var =somevar, due to the lack of setter method will cause the program to crash , or when running to Somevar = Var, the lack of getter method can also cause a crash. Compile-time is no problem, the runtime executes the corresponding method, which is called dynamic binding.

In 3.APPDELEGATE.M

_window =*view1= = = view1;[ _window makekeyandvisible];

In 4.view1controller.h

#import <UIKit/UIKit.h>#import <CoreData/CoreData.h>#import"  AppDelegate.h"#import"User.h"@interface  *myappdelegate;//Create this view remember to pass the value over @end

In 5.VIEW1CONTROLLER.M

#import "View1Controller.h"@interfaceView1controller () <UITextFieldDelegate>@property (Weak, nonatomic) Iboutlet Uitextfield*NAMETF, @property (weak, nonatomic) Iboutlet Uitextfield*AGETF, @property (weak, nonatomic) Iboutlet Uitextfield*SEXTF, @property (weak, nonatomic) Iboutlet Uitextview*serchcontent;@end@implementationView1controller- (void) viewdidload {[Super viewdidload]; //additional setup after loading the view, typically from a nib.}#pragmamark-click//Save Data-(Ibaction) SaveData: (ID) Sender {User*user = (user *) [nsentitydescription insertnewobjectforentityforname:@"User"InManagedObjectContext:self.myAppdelegate.managedObjectContext];    [User SetName:self.nameTF.text];    [User setage:@ ([self.ageTF.text integervalue]);    [User SetSex:self.sexTF.text]; [User setbirth:[nsdate Datewithtimeintervalsincenow:100000]]; [Self savestatus];}
Querying Data-(Ibaction) Serchdata: (ID) Sender {nsfetchrequest*request =[[Nsfetchrequest alloc]init]; Nsentitydescription*user = [Nsentitydescription entityforname:@"User"InManagedObjectContext:self.myAppdelegate.managedObjectContext]; [Request Setentity:user]; Nserror*error; Nsarray*mutablefetchresult = [Self.myAppdelegate.managedObjectContext executefetchrequest:request error:&ERROR]; if(Mutablefetchresult = =Nil) {NSLog (@"seach fail"); } NSLog (@"CoreData entity count is%ld", [Mutablefetchresult Count]); Nsmutablestring*string=[[Nsmutablestring alloc]init]; for(User *userinchMutablefetchresult) { [stringAppendFormat:@"name =%@,age =%@,sex =%@,birthday =%@", User.name,user.age,user.sex,user.birth]; [stringAppendFormat:@"\ n"]; } Self.serchContent.text=string;} Update Data-(Ibaction) UpdateData: (ID) Sender {nsfetchrequest*request =[[Nsfetchrequest alloc]init]; Nsentitydescription*user = [Nsentitydescription entityforname:@"User"InManagedObjectContext:self.myAppdelegate.managedObjectContext]; [Request Setentity:user]; Nserror*error; Set query condition Nspredicate (predicate): query statement nspredicate*predicate = [Nspredicate predicatewithformat:@"name =%@", Self.nameTF.text]; [Request Setpredicate:predicate]; Nsarray*mutabelfetchresult = [Self.myAppdelegate.managedObjectContext executefetchrequest:request error:&ERROR]; if(Mutabelfetchresult = =Nil) {NSLog (@"seach fail"); } NSLog (@"CoreData entity count is%ld", Mutabelfetchresult.count); for(User *userinchMutabelfetchresult) {[User setage:@ ([self.ageTF.text integervalue])]; } [self savestatus];}
Delete Data-(Ibaction) Canceldata: (ID) Sender {nsfetchrequest*request =[[Nsfetchrequest alloc]init]; Nsentitydescription*user = [Nsentitydescription entityforname:@"User"InManagedObjectContext:self.myAppdelegate.managedObjectContext]; [Request Setentity:user]; Nspredicate*predicate = [Nspredicate predicatewithformat:@"name =%@", Self.nameTF.text]; [Request Setpredicate:predicate]; Nserror*error; Nsarray*mutablefetchresult = [Self.myAppdelegate.managedObjectContext executefetchrequest:request error:&ERROR]; if(Mutablefetchresult = =Nil) {NSLog (@"Search Fail"); } NSLog (@"CoreData entity count is%ld", Mutablefetchresult.count); for(User *userinchMutablefetchresult) {[Self.myAppdelegate.managedObjectContext deleteobject:user]; } [self savestatus];} Data is saved successfully- (void) savestatus{Nserror*error; BOOL issuccess= [Self.myAppdelegate.managedObjectContext save:&ERROR]; if(!issuccess) {NSLog (@"Save fail"); }Else{NSLog (@"Save Success"); }}-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{[TextField Resignfirstresponder]; returnYES; }

Core Data uses

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.