6

我想比较 2NSMutableArray并将不同的对象放入第三个Array。我怎样才能做到这一点 ?

Array1 可以循环对象。

Array1 = "a", "b","c","d","a","b","c";
Array2 = "a", "b", "c";

然后结果

Array3 = "d";

提前致谢

4

4 回答 4

21

使用集合进行集合操作:

NSSet *set1 = [NSSet setWithArray:array1];
NSMutableSet *set2 = [NSMutableSet setWithArray:array2];
[set2 minusSet:set1];
于 2013-07-12T09:29:27.097 回答
7

你也可以试试这个。

NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"1", nil];
NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:@"2",@"1", nil];    

NSMutableArray *largeArray;
NSMutableArray *shortArray;
if([array1 count] > [array2 count]){
    largeArray = array1;
    shortArray = array2; 
} else {
    largeArray = array2;
    shortArray = array1; 
}
[largeArray removeObjectsInArray:shortArray];

for (NSString *va in largeArray) {
    NSLog(@"%@",va);
}
于 2013-07-12T09:36:09.893 回答
5
NSMutableArray *gotDiffArry= [[NSMutableArray alloc] init];
for(int i = 0 ; i < FirstArray.count; i++) {
    if(i < seconArray.count){
        if(![seconArray[i] isEqual:firstArray[i]]){
             [gotDiffArry addObject:[NSNumber numberWithInt:i]];
         }
    } else {
        [gotDiffArry addObject:[NSNumber numberWithInt:i]];
    }
}

编辑:

for (int i = 0 ; i < firstArray.count ; i ++)
{

 NSString *search = [firstArray objectAtIndex:i];
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF CONTAINS %@", search];
 NSMutableArray *temAraay = [secondArray filteredArrayUsingPredicate: predicate];
 if(temArray.count >=0 )
 {
   NSLog("%@", [temArray objectAtIndex:0]); 
 }
}
于 2013-07-12T09:32:56.843 回答
4

我使用了以下内容并获得了预期的结果:

for(int i =0; i<[arraytwo count]; i++)
{
    if (![arrayone containsObject:[arraytwo objectAtIndex:i]])
        [arraythree addObject: [arraytwo obectAtIndex:i]];
}    
NSLog(@"%@",arraythree);
于 2013-07-12T10:56:16.100 回答