从NSArray获取独特物品

时间:2015-02-17 12:14:32

标签: ios objective-c

我有一个对象GroceryItem,其定义如下:

@interface GroceryItem : NSObject
{

}

@property (nonatomic,assign) int groceryItemId;
@property (nonatomic,copy) NSString *title;


@property (nonatomic,strong) GroceryItemCategory *groceryItemCategory;

@end

现在,我需要从groceryItems集合中检索所有独特的杂货类别。我使用以下代码:

 NSSet *uniqueGroceryItemCategories = [NSSet setWithArray:[_groceryItems valueForKey:@"groceryItemCategory.title"]];

但它引发了以下异常:

[<GroceryItem 0x7fea8d82b5a0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key groceryItemCategory.title.'

title是在GroceryItemCategory类中定义的属性,它的类型为string,就像它在GroceryItem类中定义一样。

更新:

我刚刚使用KeyPath,它似​​乎正在运行:

 NSArray *array = [_groceryItems valueForKeyPath:@"groceryItemCategory.title"];

1 个答案:

答案 0 :(得分:0)

看看Collection Operators。您应该可以使用@distinctUnionOfObjects,如下所示:

NSArray *array = [_groceryItems valueForKeyPath:@"@distinctUnionOfObjects.groceryItemCategory.title"];