Help me to get the result based on condition
I have created a Users class based on NSManagedObject with following attributes (id,name,age etc).
I am using the core data model but i am not sure how to do the follwing...
Now i would like to know How c开发者_开发百科an i get the user detail based on user id.
example: select * from users where id = 1
please help me out.
You should use NSPredicate
class for executing SQL commands. The code:
NSManagedObjectContext *context = self.managedObjectContext; // specify your MOC object
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"users" inManagedObjectContext:context]; // specify your entity (table)
NSPredicate *predicate = [NSPredicate predicatewithFormat:@"id == %d",yourID]; // specify your 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: do whatever you want
}
Step 1: Alloc/init NSFetchRequest
You need to alloc/init a NSFetchRequest object if you want to execute queries.
Step 2: Select entity
If you want to specify select * from users ...
, you should use NSEntityDescription
:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"users" inManagedObjectContext:context];
At the end you need to 'attach' your entity description to your NSFetchRequest object via:
[fetchRequest setEntity:entity];
Step 3: Condition
If you want to have a condition (e.g. ... where id = 1
), you have to implement NSPredicate
.
NSPredicate *predicate = [NSPredicate predicatewithFormat:@"id == %d",yourID];
yourID
must be a 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 the records that meet the conditions will be returned as array of NSManagedObjects.
Step 5: Release objects
[entity release];
[predicate release];
[fetchRequest release];
Step 6: Do something
If there are no objects that meet the conditions, array
object will be nil
. You can check it and deal with the error via:
if (array == nil)
Check out Core Data Programming Guide for more info. :)
精彩评论