objective-c - 将实例的一个属性与一组其他实例进行比较

标签 objective-c cocoa comparison

我正在尝试为 Card 类编写一个实例方法,用于将单个卡与数组进行比较。该类具有一些属性,例如:shapecolor。 otherCards 数组填充了此类的其他实例,这些实例也有其 shapecolor

现在,我想编写一个可以单独检查所有这些属性的方法。如何传入特定属性,如:[allAttributesIsEqual:otherCardscompareWith: self.shape]?那么实际比较时我可以传入 self.shapeself.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/

相关文章:

ios - 单击按钮时如何激活 UISearchDisplayController

objective-c - 从我的 cocoa 应用程序将文件附加到 Mail.app 中的空白电子邮件

cocoa - NSTextView 在深色模式下在几乎黑色上绘制黑色

c# - 自定义排序(三个字段上的 IComparer)

php - 从搜索字符串 PHP 中删除常用词

c++ - Fmod 函数显然输出预期的 double 值,但 if(fmod == expected double) 的计算结果不为真

objective-c - 要实现 KVC 验证方法,请覆盖 -(BOOL)validateIvar :error: or -validateValue:forKey:error:?

objective-c - 使用连接的 NSString 执行选择器以查找 UIImageView

ios - NSRefreshedObjectsKey 的用途

macos - 以编程方式检查 OS X 中是否存在事件的以太网连接?