问题
If I have a couple of NSArrays filled with ints, or NSNumbers, like so:
A: { 12, 23, 45, 56, 67, 78, 99, 234 }
B: { 12, 56, 78, 99, 454, 512 }
How do I output an array with numbers that are in A but not in B, like
{ 23, 45, 67, 234 }
回答1:
What you are tying to do is purely a set operation. So you can use NSSet here. You should do minusSet:
to get the result you want.
NSMutableSet *resultSet = [NSMutableSet setWithArray:A];
NSSet *setB = [NSSet setWithArray:B];
// This is what you need!
[resultSet minusSet:setB];
Array *result = [resultSet allObjects];
回答2:
Create an NSMutableArray called C. Do a loop over A that tries to find each of its elements within B (using [B containsObject:elemOfA]
, which just sends the -isEqual:elemOfA
message to each member of B). If an element is found, do nothing; if an element isn't found, add it to C.
来源:https://stackoverflow.com/questions/7207805/getting-unique-numbers-from-two-arrays