[英]iOS how does NSMutableArray check if it contains NSNumber objects?
I'm writing some code that will be using NSMutableArray and storing int values within it, wrapped within NSNumbers. 我正在编写一些代码,这些代码将使用NSMutableArray并在其中存储int值,包含在NSNumbers中。
I would like to confirm that querying an iOS NSArray or NSMutableArray using new NSNumbers with same values is legal , of if I need to explicitly iterate over the array, and check if each int value is equal to the value I want to test against? 我想确认使用具有相同值的新NSNumber查询iOS NSArray或NSMutableArray是合法的 ,如果我需要显式迭代数组,并检查每个int值是否等于我想要测试的值?
This appears to work: 这似乎有效:
NSMutableArray* walkableTiles = [NSMutableArray array];
[walkableTiles addObject:@(1)];
[walkableTiles addObject:@(2)];
[walkableTiles addObject:@(3)];
if([walkableTiles containsObject:@(1)])
{
DLog(@"contains 1"); //test passes
}
if([walkableTiles containsObject:[NSNumber numberWithFloat:2.0]])
{
DLog(@"contains 2");//test passes
}
if([walkableTiles containsObject:[NSNumber numberWithInt:3]])
{
DLog(@"contains 3");//test passes
}
What you are doing is fine. 你做的很好。 Why wouldn't it be? 为什么不呢?
The containsObject:
method actually iterates over the array and calls the isEqual:
method on each object passing in the object you are checking for. containsObject:
方法实际上遍历数组并在传入要检查的对象的每个对象上调用isEqual:
方法。
BTW - there is nothing special here about using NSNumber
. 顺便说一句 - 这里没有什么特别的使用NSNumber
。 It's the same with an array of any object type. 对于任何对象类型的数组都是一样的。 As long as the object's class has a valid isEqual:
method, it will work. 只要对象的类具有有效的isEqual:
方法,它就可以工作。
Per the Apple's NSNumber documentation , you should use isEqualToNumber
: 根据Apple的NSNumber文档 ,您应该使用isEqualToNumber
:
isEqualToNumber: Returns a Boolean value that indicates whether the receiver and a given number are equal. isEqualToNumber:返回一个布尔值,指示接收方和给定数字是否相等。 - (BOOL)isEqualToNumber:(NSNumber *)aNumber - (BOOL)isEqualToNumber:(NSNumber *)aNumber
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.