As a manager, the most basic function is to delete and change the search.
1. Insert
appdelegate *app = [[uiapplication sharedapplication] delegate ]; Nsmanagedobjectcontext *context = [app Managedobjectcontext]; Nsmanagedobject *newmanagedobject = [nsentitydescription insertnewobjectforentityforname:@ " entityname " Inmanagedobjectcontext:context]; [Newmanagedobject setvalue:value Forkey: @ " propertyname " *error; if (! [Context Save:&error]) { // Handle the error ... }
2. Enquiry
Nsfetchrequest *fetchrequest =[[Nsfetchrequest alloc] init]; Nsmanagedobjectcontext*managedobjectcontext =Appdelegate.managedobjectcontext; Nsentitydescription*entity = [Nsentitydescription entityforname:@"Hero"Inmanagedobjectcontext:managedobjectcontext]; Nssortdescriptor*sortdescriptor1 =[[Nssortdescriptor alloc]initwithkey:@ "name" Ascending:yes]; Nssortdescriptor*sortdescriptor2 =[[Nssortdescriptor alloc]initwithkey:@ "secretidentity" ascending:yes]; Nsarray*sortdescriptors =[[Nsarray Alloc]initwithobjects:sortdescriptor1, SortDescriptor2, nil]; [Fetchrequest setsortdescriptors:sortdescriptors]; [Fetchrequest setentity:entity]; [Fetchrequest setfetchbatchsize: -]; Nsarray*objecs = [Context executefetchrequest:fetchrequest error:&error];if (Objets==nil | | error = NIL) {
Do the processing}
3. Modification
-(void) Applicationwillresignactive: (Nsnotification *) notification{NSLog (@"applicationwillresignactive"); //creating a Managed object ContextNsmanagedobjectcontext *context =[Appdelegate Managedobjectcontext]; Nsfetchrequest*request =[[Nsfetchrequest alloc]init]; Nsentitydescription*entitydescription = [Nsentitydescription entityforname:@"User"Inmanagedobjectcontext:context]; [Request Setentity:entitydescription]; Nsmanagedobject*user =Nil; Nserror*error; Nsarray*objets = [Context executefetchrequest:request error:&ERROR]; if(objets==Nil) {NSLog (@"there has a error!"); //do error handling } if([Objets count]>0){ //not the first time, update the dataNSLog (@"Update Action"); User= [Objets Objectatindex:0]; }Else{NSLog (@"Insert Operation"); //save for the first time, insert new datauser = [Nsentitydescription insertnewobjectforentityforname:@"User"Inmanagedobjectcontext:context]; } [user SetValue:self.serverIp.text Forkeypath:@"ServerIP"]; [User SetValue:self.userName.text Forkeypath:@"UserName"]; [Context Save:&error];}
4. Delete
Nsmanagedobjectcontext *managedobjectcontext =*if (![ Context save:&Error]) { %@,%@ ", error, [error userInfo]); Exit (-1// Fail}
5. Data Migration
When the program changes, in many simple cases, CoreData provides a lightweight automatic data migration, such as the following three scenarios can be achieved by turning on the CoreData automatic migration:
1. Simply add a field
2. Change a required field to an optional field
3. Change the optional fields to required fields (but be sure to define default values)
CoreData additions and deletions and data migration examples