繁体   English   中英

NSArray containsObject 方法

[英]NSArray containsObject method

我有一个关于 xcode 编码的简单问题,但不知道为什么事情没有像我想象的那样执行。 我有一组对象(自定义对象)。 我只想检查这个是否在数组中。 我使用了以下代码:

NSArray *collection = [[NSArray alloc] initWithObjects:A, B, C, nil]; //A, B, C are custom "Item" objects
Item *tempItem = [[Item alloc] initWithLength:1 width:2 height:3];  //3 instance variables in "Item" objects
if([collection containsObject:tempItem]) {
    NSLog(@"collection contains this item");
}

我想上述检查会给我一个积极的结果,但事实并非如此。 此外,我检查了创建的对象是否相同。

NSLog(@"L:%i W:%i H:%i", itemToCheck.length, itemToCheck.width, itemToCheck.height);
for (int i = 0, i < [collection count], i++) {
    Item *itemInArray = [collection objectAtIndex:i];
    NSLog(@"collection contains L:%i W:%i H:%i", itemInArray.length, itemInArray.width, itemInArrayheight);
}

在控制台中,这是我得到的:

L:1 W:2 H:3
collection contains L:0 W:0 H:0
collection contains L:1 W:2 H:3
collection contains L:6 W:8 H:2

显然tempItemcollection数组中,但是当我使用containsObject:来检查它时什么也没有显示。 谁能给我一些指导,我错了哪一部分? 非常感谢!

[NSArray containsObject:]的文档说:

此方法通过向每个接收器的对象发送 isEqual: 消息(并将 anObject 作为参数传递给每个 isEqual: 消息)来确定接收器中是否存在对象。

问题在于您正在比较对对象的引用而不是对象的值。 为了使这个特定示例工作,您需要发送[collection containsObject:]它包含的变量的实例(例如ABC ),或者您需要覆盖[NSObject isEqual:]方法Item类。

这就是你的isEqual方法的样子:

- (BOOL)isEqual:(id)other {
    if (other == self)
      return YES;
    if (!other || ![other isKindOfClass:[self class]])
      return NO;
    if (self.length != other.length || self.width != other.width || self.height != other.height)
      return NO;
    return YES;
}

为了更好的实现,你可能想看看这个问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM