Search code examples
xcodecore-datansfetchrequest

Xcode 8.1 core data fetching specific properties


I am trying to fetch a specific property from Core Data using the following code:

NSFetchRequest *test = [[NSFetchRequest alloc] init];
test.entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.currentMainContext];
test.predicate = [NSPredicate predicateWithFormat:@"TRUEPREDICATE"];
test.resultType = NSDictionaryResultType;
test.returnsDistinctResults = YES;
test.propertiesToFetch = @[@"property"];

NSArray *results = [self.currentMainContext executeFetchRequest:test error:error];

but I get an empty array back.

If I comment out test.resultType = NSDictionaryResultType; then I get back an array of all the entities in my database as expected. What is it about the NSDictionaryResultType that is wrong?


Solution

  • Fetch request with resultType of NSDictionaryResultType has one peculiarity.
    Documentation for includesPendingChanges states that:

    If the value is NO, the fetch request doesn't check unsaved changes and only returns objects that matched the predicate in the persistent store.

    A value of YES is not supported in conjunction with the result type NSDictionaryResultType, including calculation of aggregate results (such as max and min). For dictionaries, the array returned from the fetch reflects the current state in the persistent store, and does not take into account any pending changes, insertions, or deletions in the context.

    So make sure that you have saved your changes, or use NSManagedObjectResultType.