Core data Fetch Request returning wrong number of records
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.
SELECT DISTINCT ZPROPERTYNAME FROM ZENTITY WHERE ZCONPROP1 == 2 AND ZCONPROP2='aValue'
I verified that whatever I was doing was correct.
Then I tried altering the values of NSPredicate string. Thats where the root cause was.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@”prop1==%d AND prop2==%@”,value1,value2];
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.