Objective-C检查带有int的数组是否包含int

时间:2013-10-09 19:13:04

标签: ios objective-c arrays int

伙计们,我正在努力做到以下几点。 我有一个名为'specialLevels'的数组(NSArray),该数组看起来像这样:

specialLevels = @[@2, @4, @6, @9];

这应该是一个int数组。 我也得到了int'urrentLevel'(基本int无对象)。

我想检查currentLevel是否在特殊级别的de数组中。 我知道方法'containsObject'存在,但这在我的情况下不起作用。

在这种情况下,你们会建议做什么?

所以我想到了这一点,但感觉有点奇怪:

if ([specialLevels containsObject:[NSNumber numberWithInt:currentLevel]]) {
 // other code in here
}

2 个答案:

答案 0 :(得分:19)

你也可以写:

if ([specialLevels containsObject:@(currentLevel)]) {
    // other code in here
}

更符合其他代码的风格。

答案 1 :(得分:13)

specialLevels不是一个int数组。它是一个NSNumber对象的数组。 @ 2,@ 4,@ 6,@ 8各创建一个等同于调用[[NSNumber numberWithInt:value]的NSNumber实例。当您调用containsObject时,您还需要传递一个NSNumber对象,以便containsObject可以匹配该值(使用isEqual:)。

您可以阅读Objective-C literals here