Francis S
Francis S

Reputation: 183

how to query using NSpredicate

I am new to xcode and core data. I want to perform the following query using core data.

Select count(roomtype)from roomtable where roomtype=@"ac single" and roomstatus=@"YES";

Please guide me how to use the NSPredicate to perform my query.

Upvotes: 0

Views: 77

Answers (1)

Abizern
Abizern

Reputation: 150615

Steps with dealing with Core Data are:

Create a fetch request to pull objects into the managed object context

// Assuming you have an entity called Rooms:
[NSFetchRequest fetchRequestWithEntityName:@"Rooms"];

Now create the predicates to be applied to that entity to filter what is returned

// Assuming that the Rooms entity has attributes for "roomType" and "roomStatus"
// I'd actually use %K and attributes - but this will do until you learn about them.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomType == %@ and roomStatus == %@", @"ac single", @"YES"];

[request setPredicate:predicate];

Run the fetch request

// Assuming you have the managed Object Context in a property
NSError *error;
NSArray *results = [self.moc executeFetchRequest:request error:&error];

// Make sure the results are not nil, if they are handle the error
if (!results) {
    // Handle error in here using the error parameter you passed in by reference.
}

The results are now in an array and you can get the number of entities that satisfy the predicate simply with:

NSUInteger resultCount = [results count];

This is all standard stuff when working with Core Data. If you work your way through it and try to understand the steps - you'll be a long way to writing your own fetch requests.

Upvotes: 1

Related Questions