0

我有具有以下值的 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 的每个对象或值进行比较。

4

6 回答 6

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.
        } 
    }
}
于 2012-05-31T08:43:33.383 回答
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]];
    }
}
于 2012-05-31T08:47:22.980 回答
1

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

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

我想这会对你有所帮助

快乐编码 :) 享受它 :)

于 2012-05-31T08:45:42.737 回答
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
        }
    }
于 2012-05-31T08:50:46.307 回答
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");
        }
    }
于 2012-05-31T09:17:21.217 回答
0

NSArray 中有一个 isEqualToArray 方法。你能不能像下面这样使用它:

[array1 isEqualToArray:array2]

于 2012-10-16T18:19:35.637 回答