objective c - delete and Update Data in Core Data in iOS -
hi newbie in core data in ios, have implemented 4 textfields namely name,age,company,address. when user enter data saving data in core data.
nsmanagedobjectcontext *context = [appdelegate managedobjectcontext]; nsmanagedobject *newcontact; newcontact = [nsentitydescription insertnewobjectforentityforname:@"device" inmanagedobjectcontext:context]; [newcontact setvalue: _name.text forkey:@"name"]; [newcontact setvalue: _address.text forkey:@"address"]; [newcontact setvalue: _age.text forkey:@"age"]; [newcontact setvalue:_company.text forkey:@"company
similarly able fetch , display data in these textfields.
appdelegate *appdelegate = [[uiapplication sharedapplication] delegate];
nsmanagedobjectcontext *context = [appdelegate managedobjectcontext]; nsentitydescription *entitydesc = [nsentitydescription entityforname:@"device" inmanagedobjectcontext:context]; nsfetchrequest *request = [[nsfetchrequest alloc] init]; [request setentity:entitydesc]; nspredicate *pred = [nspredicate predicatewithformat:@"(name = %@)", _name.text]; [request setpredicate:pred]; nsmanagedobject *matches = nil; nserror *error; nsarray *objects = [context executefetchrequest:request error:&error];matches = objects[0]; _address.text = [matches valueforkey:@"address"]; _age.text = [matches valueforkey:@"age"]; _company.text = [matches valueforkey:@"company"];
now while want delete , update data of particular user not able fetch data.
how can delete data , update ..?
i have gone through link http://www.appcoda.com/core-data-tutorial-update-delete/
thank in advance
you can delete data :
nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; nsentitydescription *entity = [nsentitydescription entityforname:@"entityname" inmanagedobjectcontext:context]; nspredicate *predicate = [nspredicate predicatewithformat:@"userid %@",userid]; [fetchrequest setentity:entity]; [fetchrequest setpredicate:predicate]; nserror *error; nsarray *items = [context executefetchrequest:fetchrequest error:&error]; (nsmanagedobject *managedobject in items) { [context deleteobject:managedobject]; }
and update :
nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; nsentitydescription *entity = [nsentitydescription entityforname:@"entityname" inmanagedobjectcontext:context]; nspredicate *predicate = [nspredicate predicatewithformat:@"userid %@",userid]; [fetchrequest setpredicate:predicate]; [fetchrequest setfetchlimit:1]; [fetchrequest setentity:entity]; nserror *error; nsarray *arrresult = [context executefetchrequest:fetchrequest error:&error]; yourentityname *entity = arrresult[0]; entity.userid = @"2" [appdelegate savecontext];
Comments
Post a Comment