NSArray containsObject方法

Ant*_*ony 17 arrays iphone xcode compare

我有一个关于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");
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

显然tempItem是在collection数组内部,但是当我containsObject:用来检查它时没有任何显示.任何人都可以给我一些指示我错了吗?非常感谢!

Sen*_*ful 41

文档[NSArray containsObject:]说:

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

问题是您正在比较对象的引用而不是对象的值.为了使这个具体的例子工作,你要么需要发送[collection containsObject:]它包含一个变量(例如实例A,BC),或者你需要重写[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;
}
Run Code Online (Sandbox Code Playgroud)

为了更好地实现,您可能需要查看此问题.

  • 它确实有效,只是使用对自定义对象的引用进行默认比较.如果你想在上面的例子中使`tempItem`等于'A`,你需要在你的类上简单地创建`isEqual`方法. (2认同)