Reputation: 1855
I have to 2 NSMutableArray
s containing NSMutableDictionary
s. I need to verify the dictionaries in one of the arrays exists in the other array. How can I do this?
Upvotes: 0
Views: 1618
Reputation: 469
I'm not sure if this is the best approach but it is an easy one. I created a method to verify if a NSDictionary
is present inside a NSArray
. Inside this function, I convert the NSDictionary
s to NSString
s and compare them.
- (BOOL)verifyIfDictionary:(NSDictionary *)dict existsInsideArray:(NSArray *)array
{
BOOL result = NO;
NSString *dictStr = [NSString stringWithFormat:@"%@",dict]; // convert dictionary to string
for (NSDictionary *d in arrayOfDictionaries)
{
NSString *dStr = [NSString stringWithFormat:@"%@",dict]; // same conversion as above conversion
// now, I just have to compare the resulting strings
if ([dictStr isEqualToString:dStr])
result = YES;
}
return result;
}
Now you just have to iterate through one of your NSArray
s and use this method, like this:
NSArray *arrayOfDictionaries1;
NSArray *arrayOfDictionaries2;
// initialize them, fill with data, do your processing.. etc, etc...
// then, when you want to verify:
for (NSDictionary *dict in arrayOfDictionaries1)
{
if ([self verifyIfDictionary:dict existsInsideArray:arrayOfDictionaries2])
{
NSLog(@"exists!");
}
}
Upvotes: 4
Reputation: 119031
To check if array1
contains all of the items in array2
:
NSMutableArray *mutableArrayToCheck = [array2 mutableCopy];
[mutableArrayToCheck removeObjectsInArray:array1];
if (array2.count > 0 && mutableArrayToCheck.count == 0) {
// array2 contains all the items in array1
}
Ignore the type of the contents of the arrays for a second, just think of numbers. We have 2 arrays:
array1 = [ 1, 2, 3 ]
array2 = [ 1, 3 ]
If we remove the items in array1 from array2, and the result is an empty array, then we know that all of the items in array2 were also in array1.
removeObjectsInArray:
does this for us by searching through the array and comparing each item. We just need to check the result.
This works no matter what the contents of the array are, so long as they implement hash
and isEqual:
.
Upvotes: 0