0

我有两个 MutableArray 值,例如。

NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", @"Banana", nil];

NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", nil];

现在我必须比较这两个可变数组并将那个不匹配的对象“香蕉”显示为一个字符串。

我对 iOS 比较陌生,所以任何人都会向我发送该问题的代码。

提前致谢。

4

4 回答 4

2

正如其他人所建议的那样,NSSet 可能是您最好的选择。但是,鉴于 *array 是可变的,您可以简单地从中删除 *array1 中包含的对象

NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", @"Banana", nil];
NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", nil];

[array removeObjectsInArray:array1];
NSLog(@"array: %@", array);         //  array: ( Banana )

// if you require result as a string
NSString *objectsAsString = [array componentsJoinedByString:@", "];
NSLog(@"objects as string: %@", objectsAsString);   // objects as string: Banana
于 2013-09-24T05:57:26.163 回答
0
    for(int i=0;i<[array count];i++)
    {

    NSString *str1 = [array objectAtIndex:i];
    for(int j=0;j<[array1 count];j++)
    {

    NSString *str2 = [array1 objectAtIndex:j];
     if([str1 isEqualToString:str2])
    {
    //do something which you want i.e add the values to some other array
    }
    }

}
于 2013-09-24T05:55:04.097 回答
0

您可能应该NSSet用于此目的

NSSet *set1 = [NSSet setWithObjects:@"a", @"s", @"d", @"f", nil];
NSSet *set2 = [NSSet setWithObjects:@"a", @"s", nil];

NSMutableSet *notInSet1 = [NSMutableSet setWithSet:set2];
[notInSet1 minusSet:set1];
NSMutableSet *notInSet2 = [NSMutableSet setWithSet:set1];
[notInSet2 minusSet:set2];

NSMutableSet *symmetricDifference = [NSMutableSet setWithSet:notInSet1];
[symmetricDifference unionSet:notInSet2];
于 2013-09-24T05:55:12.713 回答
0
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil];
NSMutableArray *ary_result = [[NSMutableArray alloc] init];
NSMutableArray *ary_resultUnmatched = [[NSMutableArray alloc] init];
for(int i = 0;i<[array1 count];i++)
{
    for(int j= 0;j<[array2 count];j++)
    {
        if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]])
        {
            [ary_result addObject:[array1 objectAtIndex:i]];
        } else {
            [ary_resultUnmatched addObject:[array1 objectAtIndex:i]];
        }
    }
}
NSLog(@"%@",ary_result);//it will print a,c
NSLog(@"%@",ary_resultUnmatched);//it will print b,d

所以在其他情况下,您将获得不匹配的值

于 2013-09-24T05:55:28.593 回答