NSArray containsObject方法 [英] NSArray containsObject method

查看:147
本文介绍了NSArray containsObject方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple question regarding xcode coding but don't know why things are not performing as I think. I have an array of objects (custom objects). I just want to check if this one is within the array. I used the following code:

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");
}

我想上面的检查会给我一个肯定的结果,但它不是。此外,我检查创建的对象是否相同。

I suppose the above checking will give me a positive result but it's not. Further, I checked whether the objects created are the same.

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);
}



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

In the console, this is what I got:

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

显然 tempItem 集合数组内,但是当我使用 来检查它。任何人都可以给我一些方向,哪一部分我错了?非常感谢。

Obviously the tempItem is inside the collection array but nothing shows up when I use containsObject: to check it. Could anyone give me some direction which part I am wrong? Thanks a lot!

推荐答案

[NSArray containsObject:] 说:


此方法确定
anObject是否存在于接收者
发送一个isEqual:消息给每个
接收者的对象(并传递
anObject作为参数到每个
isEqual:message)。

This method determines whether anObject is present in the receiver by sending an isEqual: message to each of the receiver’s objects (and passing anObject as the parameter to each isEqual: message).

问题是你正在比较对象的引用,而不是对象的值。为了使这个具体的例子工作,你将需要发送 [collection containsObject:] 它包含的变量的实例(例如 A B C ),否则您将需要覆盖 Item 类中的 [NSObject isEqual:] 方法。

The problem is that you are comparing references to objects rather than the values of the objects. To make this specific example work, you will either need to send [collection containsObject:] an instance of a variable it contains (e.g. A, B, or C), or you will need to override the [NSObject isEqual:] method in your Item class.

这是您的 isEqual 方法可能如下所示:

This is what your isEqual method might look like:

- (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;
}

为了更好的实现,你可能想看看查询

For a better implementation, you may want to look at this question.

这篇关于NSArray containsObject方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆