Check if the dictionary is present in the dictionary array?

I have a set of dictionaries containing the same keys, but different meanings. I have another dictionary, and I want to check if this dictionary is present in this array or not ... ???

+4
source share
2 answers

Suppose you have three keys in the sesond dictionary key1, key2, key3, so to check for Dictionay in the ayour array, use the "NSPredicate" class like this. Suppose your array is _myDicArray and the other dictionary is _refDic

NSPredicate* myPredicate =[NSPredicate predicateWithFormat:@"key1 like %@ AND key2 like %@ AND key3 like %@",[_refDic objectForKey:@"key1"],[_refDic objectForKey:@"key2"],[_refDic objectForKey:@"key3"]]; NSArray* someOtherArr = [[_myDicArray filteredArrayUsingPredicate:filmPredicate] objectAtIndex:0]; if([someOtherArr count] > 0) //this is what you wanted ... this array has ur dic 

I think this should also work.

  NSPredicate* myPredicate =[NSPredicate predicateWithFormat:@"self == %@",_refDic]; NSArray* someOtherArr = [[_myDicArray filteredArrayUsingPredicate:filmPredicate] objectAtIndex:0]; if([someOtherArr count] > 0) //this is what you wanted ... this array has ur dic 
+1
source

Well, I would implement it that way.

Subclass NSDictionary and execute the following methods:

 - (BOOL)isEqual:(id)object; - (NSUInteger)hash; 

It is very important that you implement the hash correctly. It should return different values ​​for different dictionaries, even if they are equal according to your definition. In isEqual, you can check if both dictionaries contain the same keys and the same values. If yes, return YES, otherwise return NO.

With this, your check later will be only one line: [arrayOfDictionaries containsObject:dictionaryIAmLookingFor];

If you implement the hash incorrectly or do not implement it, containsObject will not execute isEqual for all objects in the array.

+1
source

All Articles