About [NSArray containsObject:]

本文详细解释了在Swift中使用NSArray的containsObject:方法时,为何会误将对象的引用进行比较,而不是其实际值。并提供了解决方案,包括使用collection.contains或者覆盖NSObject的isEqual方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

he documentation for [NSArray containsObject:] says:

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).

The documentation for [NSArray containsObject:] says:

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).

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 Fruit class.

转载:http://stackoverflow.com/questions/2941596/nsarray-containobjects-method

//先遍历,去掉已收到最新已读状态的会话id;或者轮询次数大于10次的会话id NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet]; //创建一个新数组用于遍历,避免遍历期间修改,导致崩溃 // NSArray *tempArray = [NSArray arrayWithArray:self.waitToUpdateDialoguesArray]; YYThreadSafeArray *tempArray = [YYThreadSafeArray arrayWithArray:self.waitToUpdateDialoguesArray]; // @synchronized (tempArray) { //开始遍历 for (NSString *dialogueId in tempArray) { //增加判断,避免indexOfObject越界 if ([dialogueId integerValue] < self.dialogueCheckCountDic.count) { //对应的会话在当前连接中,是否收到了headline消息 if ([self.didReceiveIQMessageDialogueIdArray containsObject:dialogueId] || //或者轮询次数大于10次 [[self.dialogueCheckCountDic objectForKey:dialogueId] integerValue]>10) { if ([self.waitToUpdateDialoguesArray indexOfObject:dialogueId] != NSNotFound) { [indexSet addIndex:[self.waitToUpdateDialoguesArray indexOfObject:dialogueId]]; } } } } //如果有需要移除的,就移除掉 //并且确保临时数组与waitToUpdateDialoguesArray数量相同,避免被修改后越界修改 if (indexSet.count >0 && tempArray.count == self.waitToUpdateDialoguesArray.count) { [self.waitToUpdateDialoguesArray removeObjectsAtIndexes:indexSet]; } } 你是ios专家, 我的app在运行中发生错误, xcode定位到以上代码发生错误并提示[NSArray initWithArray:range:copyItems:]: range {0, 2} extends beyond bounds for empty array错误, 请分析这个错误原因
07-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值