user470763
user470763

Reputation:

Return multiple values with NSPredicate

I am using NSPredicate to query a Core Data store. I have an atribute of type NSNumber. I want to get all atributes which equal 1.

I have tried:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"attribute == %i", i];

Where i = 1.

This works but it only returns the first object with the matching attribute. I want ALL objects with this attribute when it is equal to 1.

Where am I going wrong? I tried putting ALL in front of the query but that caused a crash.

Update:

This is my full code:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person"
                                          inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setResultType:NSDictionaryResultType];

NSNumber *attributeValue = [NSNumber numberWithInt:1];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"attribute == %@",
                          attributeValue];
[fetchRequest setPredicate:predicate];

NSError *error = nil;
NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest
                                                                 error:&error];

return [fetchResults objectAtIndex:0];

And then:

NSDictionary *dict = [self queryContextWithQuery:nil];
NSLog(@"%@", dict);

The log only shows 1 out of the 3 possible objects it should show.

Upvotes: 1

Views: 407

Answers (3)

user470763
user470763

Reputation:

It turns out the problem wasn't with the query. It was with how I was returning the result. I modified the method to return an array instead of a dictionary and changed:

return [fetchResults objectAtIndex:0];

To:

return fetchResults;

And now I am getting the correct results.

Upvotes: 0

Oscar Gomez
Oscar Gomez

Reputation: 18488

Try this:

NSNumber *attributeValue = [NSNumber numberWithInt:1];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myAttr == %@",
        attributeValue];

Upvotes: 0

Michael Frederick
Michael Frederick

Reputation: 16714

This should work:

NSNumber *attributeValue = [NSNumber numberWithInt:1];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"attribute == %@",
        attributeValue];

Upvotes: 0

Related Questions