Skip to content

Core data Fetch Request returning wrong number of records

December 27, 2013

I  am using Core data’s NSFetchRequest to extract all distinct values of a column from a Table. Sometimes I would need to extract all the items without any NSPredicate  and sometimes with the predicate.

So I started getting two weird problems when I  used the below code:

NSEntityDescription *entity = [NSEntityDescription  entityForName:@"EntityName" inManagedObjectContext:coreDataContext];

NSFetchRequest *request = [[NSFetchRequest alloc]init];

[request setEntity:entity];

[request setPredicate:predicate];

[request setResultType:NSDictionaryResultType];

[request setReturnsDistinctResults:YES];

[request setPropertiesToFetch:[NSArray arrayWithObject:propertyName] ];

// Execute the fetch.

NSError *error;

NSArray *objects = [coreDataContext executeFetchRequest:request error:&error];

The expected Result:

An array of the NSDictionary-ies with key being the name of the property which we are searching for and the value being the unique value of the property.

Problems I faced:

1. There was an extra record appearing in the result array with an empty key and a value. All other records will had the unique values . (This occurred when I use a single property condition check in NSPredicate)

2. The result always had only 1 record irrespective of the number of unique values.

I used the sqlite queries to check if what I am doing is correct.


I verified that whatever I was doing was correct.

Then I tried altering the values of NSPredicate string. Thats where the root cause was.

valid NSPredicate:

NSPredicate *predicate  =  [NSPredicate predicateWithFormat:@”prop1==%d AND prop2==%@”,value1,value2];

Invalid NSPredicate:

NSPredicate *predicate  =  [NSPredicate predicateWithFormat:@”prop1 == %d AND prop2 ==  %@”,value1,value2];

Not much difference between the two predicates right? Yes, except the spaces between property name and == operator and the value.

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: