我正在尝试为 Card
类编写一个实例方法,用于将单个卡与数组进行比较。该类具有一些属性,例如:shape
和 color
。 otherCards 数组填充了此类的其他实例,这些实例也有其 shape
和 color
。
现在,我想编写一个可以单独检查所有这些属性的方法。如何传入特定属性,如:[allAttributesIsEqual:otherCardscompareWith: self.shape]
?那么实际比较时我可以传入 self.shape
或 self.color
吗?
- (BOOL)allAttributesIsEqual: (NSArray *)otherCards
{
//self.shape is equal to othercards.shape
}
最佳答案
你不能直接传入self.shape
,因为这将为您提供属性的值。不过,多亏了 Cocoa/ObjC 的一些强大功能,您可以传入属性(或方法)的名称并稍后获取结果。
聪明的(我敢说,甚至可能是“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;
然而,对于您感兴趣的每处特性来说,这并不是一个坏主意。当然,其中每一个都可以调用基本的“聪明”版本。
关于objective-c - 将实例的一个属性与一组其他实例进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14903020/