您應該使用後備存儲來幫助您獲得不同的記錄。
如果你想獲得一個數組只有約翰,貝蒂,愛德華這裏是你如何做到這一點:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.managedObjectContext];
// Required! Unless you set the resultType to NSDictionaryResultType, distinct can't work.
// All objects in the backing store are implicitly distinct, but two dictionaries can be duplicates.
// Since you only want distinct names, only ask for the 'name' property.
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]];
fetchRequest.returnsDistinctResults = YES;
// Now it should yield an NSArray of distinct values in dictionaries.
NSArray *dictionaries = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSLog (@"names: %@",dictionaries);
AlleyGator,但是如果我有多個具有相同屬性的對象(如示例中的多個Betty),並且我不'不想重複價值觀? –
這會給你一個三個名字的數組,沒有重複。沒有其他數據。沒有速度,沒有因素。 – AlleyGator
我錯過了returnsDistinctResults屬性。謝謝。 Upvoted的答案,但NSArray沒有'allValues'方法。所以我仍然需要做一個for循環來獲取數組中每個NSDictionary的每個值。 –