你不能只传入self.shape
,因为这会给你财产的价值。不过,感谢 Cocoa/ObjC 的一些 dynamite,您可以传入属性(或方法)的名称并稍后获取结果。
聪明的(我敢说,甚至可能是“Pythonic”)方式:
// The name of the property we're interested in.
NSString * key = @"color";
// Get the values of that property for all the Cards in the array, then
// collapse duplicates, because they'll give the same results when comparing
// with the single card.
NSSet * vals = [NSSet setWithArray:[arrayOfCards valueForKey:key]];
// Now, if the set has only one member, and this member is the same
// as the appropriate value of the card we already have, all objects
// in the array have the same value for the property we're looking at.
BOOL colorIsEqual = ([vals count] == 1 && [vals containsObject:[myCard valueForKey:key]]);
然后你的方法可以如下所示:
- (BOOL)allOtherCards: (NSArray *)otherCards haveEqualAttribute: (NSString *)key;
然而, Dan F 建议为- (BOOL)<#property#>Equal: (NSArray *)otherCards;
您感兴趣的每个属性实施这一点并不是一个坏主意。当然,这些中的每一个都可以调用基本的“聪明”版本。