I have two different NSMutabelArray ArrOne and ArrTwo. Letsay ArrOne = A, B, C and D ArrTwo = C, D, X and Y. So i need to check if the value of ArrTwo is same as ArrOne and remove item from ArrTwo if it is not same as in ArrOne. In this case, i have to remove X and Y from ArrTwo. Please give me an idea.
3 Answers
NSMutableSet *set = [NSMutableSet setWithArray:arrOne];
[set intersectSet:[NSSet setWithAray:arrTwo];
return [set allObjects];
-
+1, but you didnt completely answer the question. You need to add
[ArrTwo removeObjectsInArray:[set allObjects]];
as well.– iDevCommented Mar 8, 2013 at 3:07 -
This will only return intersect value. How can I know which one I should delete. Commented Mar 8, 2013 at 3:42
-
1@bobShawal, You can use
[ArrTwo removeObjectsInArray:[set allObjects]];
after the above code instead of replace. Or else check the answer which will also work for you.– iDevCommented Mar 8, 2013 at 4:09 -
The answer is correct. If he removes the values in the set from arrTwo he gets the an array containing the values that ARE NOT in arrOne. But that's not what the user asked. Commented Mar 12, 2014 at 9:38
You can do it with indexesOfObjectsPassingTest, like this:
NSMutableArray *a = [@[@"A",@"B",@"C",@"D"] mutableCopy];
NSMutableArray *b = [@[@"C",@"D",@"X",@"Y"] mutableCopy];
NSIndexSet *indxs = [b indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
return ![a containsObject:obj];
}];
[b removeObjectsAtIndexes:indxs];
I found a solution and it works
for (int i=0; i< arrTwo.count; i++)
{
if(![arrOne containsObject:[arrTwo objectAtIndex:i]])
{
//do action
NSLog(@"do delete %@",[arrTwo objectAtIndex:i]);
}
}
Thanks!