NSArray和NSInteger比较

时间:2017-01-29 11:23:58

标签: ios objective-c iphone

NSArray *array=[[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];

NSNumber *j = @(1);

for(id i in array) {

    if ([i isEqual:j])// always executes an else..I don't know why
    {
        NSLog(@"This object is matching %@",i);
    }
    else
    {
        NSLog(@"This Object is missing %@",i);
    }
    j = @([j intValue] + 1);
}

代码总是执行else。我不知道为什么。我想检查数组元素列表中是否有一些缺失

2 个答案:

答案 0 :(得分:1)

您正在使用@"..."将字符串放入数组中,但您应该输入整数:

NSArray *array=[[NSArray alloc] initWithObjects:@1,@2,@3,@4,@5,@6,@7,@8,@9,@10, nil];

答案 1 :(得分:1)

您正在将数组中的NSStringNSNumber j进行比较,因此比较总是失败

一种方法是使用stringValue代替j

NSArray *array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];

NSNumber *j = @(1);

for(NSString *i in array)
{
    if ([i isEqualToString:j.stringValue])
    {
        NSLog(@"This object is matching %@",i);            
    }
    else
    {
        NSLog(@"This Object is missing %@",i);            
    }
}