iphone - Help me to get the result based on condition -


i have created users class based on nsmanagedobject following attributes (id,name,age etc).

i using core data model not sure how follwing...

now know how can user detail based on user id.

example: select * users id = 1

please me out.

you should use nspredicate class executing sql commands. code:

nsmanagedobjectcontext *context = self.managedobjectcontext; // specify moc object  nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; nsentitydescription *entity = [nsentitydescription entityforname:@"users" inmanagedobjectcontext:context]; // specify entity (table) nspredicate *predicate = [nspredicate predicatewithformat:@"id == %d",yourid]; // specify condition (predicate)  [fetchrequest setentity:entity]; [fetchrequest setpredicate:predicate];  nserror *error = nil; nsarray *array = [context executefetchrequest:fetchrequest error:&error]; // execute  [entity release]; [predicate release]; [fetchrequest release];  if (array == nil) {     // error: no objects returned } else {     // success: whatever want } 

step 1: alloc/init nsfetchrequest

you need alloc/init nsfetchrequest object if want execute queries.

step 2: select entity

if want specify select * users ..., should use nsentitydescription:

nsentitydescription *entity = [nsentitydescription entityforname:@"users" inmanagedobjectcontext:context]; 

at end need 'attach' entity description nsfetchrequest object via:

[fetchrequest setentity:entity]; 

step 3: condition

if want have condition (e.g. ... id = 1), have implement nspredicate.

nspredicate *predicate = [nspredicate predicatewithformat:@"id == %d",yourid]; 

yourid must number (e.g. 1, 2, 7 or 46).

and, again:

[fetchrequest setpredicate:predicate]; 

step 4: let's execute it!

nsarray *array = [context executefetchrequest:fetchrequest error:&error]; 

all records meet conditions returned array of nsmanagedobjects.

step 5: release objects

[entity release]; [predicate release]; [fetchrequest release]; 

step 6: something

if there no objects meet conditions, array object nil. can check , deal error via:

if (array == nil) 

check out core data programming guide more info. :)


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -