iphone – NSArray containsObject方法

iphone – NSArray containsObject方法,第1张

概述我有一个关于xcode编码的简单问题,但不知道为什么事情不能像我想象的那样执行。我有一个对象数组(自定义对象)。我只想检查这个是否在数组内。我使用以下代码: NSArray *collection = [[NSArray alloc] initWithObjects:A, B, C, nil]; //A, B, C are custom "Item" objectsItem *tempItem 我有一个关于xcode编码的简单问题,但不知道为什么事情不能像我想象的那样执行。我有一个对象数组(自定义对象)。我只想检查这个是否在数组内。我使用以下代码:

NSArray *collection = [[NSArray alloc] initWithObjects:A,B,C,nil]; //A,C are custom "Item" objectsItem *tempItem = [[Item alloc] initWithLength:1 wIDth:2 height:3];  //3 instance variables in "Item" objectsif([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:3collection contains L:0 W:0 H:0collection contains L:1 W:2 H:3collection contains L:6 W:8 H:2

显然,tempItem是在集合数组内,但是当我使用containsObject时,没有显示出来:检查它。有人会给我一些方向哪个部分我错了吗?非常感谢!

解决方法 [NSArray containsObject:]的文档说:

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:]方法。

这是你的isqual方法可能是这样的:

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

为了更好的实施,您可能想看看这个question。

总结

以上是内存溢出为你收集整理的iphone – NSArray containsObject方法全部内容,希望文章能够帮你解决iphone – NSArray containsObject方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1070385.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存