我正在尝试编写一个实例方法Card
将单张卡与数组进行比较的类。该类具有一些属性,例如:shape
and color
. The otherCards
数组中充满了此类的其他实例,这些实例也有它们的shape
s and color
s.
现在,我想编写一个可以单独检查所有这些属性的方法。我如何传递特定属性,如:[allAttributesIsEqual:otherCards compareWith: self.shape]
?所以我可以通过self.shape
or self.color
实际比较时?
- (BOOL)allAttributesIsEqual: (NSArray *)otherCards
{
//self.shape is equal to othercards.shape
}
你不能只是通过self.shape
,因为这会给你value的财产。然而,多亏了 Cocoa/ObjC 的一些炸药,你可以传入name属性(或方法)并稍后获取结果。
聪明的(我敢说,甚至可能是“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;
然而,对于您感兴趣的每处房产来说,这并不是一个坏主意。当然,每一个都可以调用基本的“聪明”版本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)