我有一个关于xcode编码的简单问题,但不知道为什么事情不能像我想象的那样执行。我有一个对象数组(自定义对象)。我只想检查这个是否在数组内。我使用以下代码:
NSArray *collection = [[NSArray alloc] initWithObjects:A,B,C,nil]; //A,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
显然,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。