将NSMutablearray的对象与For循环值进行比较

时间:2012-05-31 08:35:32

标签: iphone ios for-loop nsmutablearray

我的NSMutableArray包含以下值:

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

这是我的For循环:

for(int i=0; i<30; i++)
{
    //here I want to compare each object from above array with value of i from for loop. and add the further output. e.g.
    if(i== object from array)
    {
          //do this
    }
}

实际上我在数组中只有五个对象或值,所以如何将i的每个值与每个对象或NSMutableArray的值进行比较。

6 个答案:

答案 0 :(得分:3)

因此,如果我理解正确,您想要将数组中的每个对象与数组中的所有其他对象进行比较?这是一个例子,不是测试,可能需要一些优化。

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

for(NSInteger i = 0; i < [array count]; i++) {
    for(NSInteger j = 0; j < [array count]; j++) {
        if ( i == j) {
           // No need to check if its the same object.
           continue;
        }

        NSString *stringI = [array objectAtIndex:i];
        NSString *stringJ = [array objectAtIndex:j];

        if ([stringI isEqualToString:stringJ) {
           // Do something.
        } 
    }
}

答案 1 :(得分:2)

如果您信任IOS功能containsObjectindexOfObject,那么:

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

for(int i = 0; i< 30; i++)
{
    if([array containsObject:[NSString stringWithFormat:@"%i",i]])
    {
        //array contains  "i" item,  
        //and we can know it's location this way:
        int foundArrayItemId = [array indexOfObject:[NSString stringWithFormat:@"%i",i]];
    }
}

答案 2 :(得分:1)

只需使用嵌套循环进行比较,如

for(i = 0; i <= [array count];i++)
    {
        for(j=0; j<=[mutableArrya count]; j++)
            {
                 //Do comparison
            }
    }

我认为这会对你有所帮助

快乐编码:) 享受它:)

答案 3 :(得分:0)

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

for(int i=0;i<30;i++)

    {
      NSString str= [NSString stringWithFormat:@"%i",i];
        if([array containsObject:str])
        {
          //do this
        }
    }

答案 4 :(得分:0)

编写此代码:

NSMutableArray *arrCount = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", nil];
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"21",@"12",@"23",@"14",@"25", nil];

    for (NSString *strComapre in array)
    {
        NSLog(@"%@",strComapre);
        if ([arrCount containsObject:strComapre]) 
        {
             NSLog(@"Compare");
        }
        else
        {
             NSLog(@"Not Compare");
        }
    }

答案 5 :(得分:0)

NSArray中有一个isEqualToArray方法。你可以不按如下方式使用它:

[array1 isEqualToArray:array2]