Check whether dictionary is present in array of Dictionaries? - iphone

I have an array of dictionaries which contains Same keys but different values.
I have another dictionary and i want to check whether this dictionary is present in that array or not…???

suppose you have three keys in your sesond dictionary key1,key2,key3 so to get verification of presence of the dictionay in ayour array use 'NSPredicate` class like this
Suppose your array is _myDicArray and 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

Well, I would implement it this way.
Create a subclass of NSDictionary and implement these methods:
- (BOOL)isEqual:(id)object;
- (NSUInteger)hash;
It's very important that you properly implement hash. 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 is later merely one line: [arrayOfDictionaries containsObject:dictionaryIAmLookingFor];
If you implement improperly hash or skip implementing it, containsObject will not execute isEqual on all the objects in the array.

Related

adding Key values from NSDictionary to NSarray

I want to add all the keys from the dictionary to the array. This is what I am doing right now.As code below:
for (NSString * akey in _groups ) {
NSLog(#"%#",akey);
[_groupArray addObject:akey];
NSLog(#"%#",_groupArray);
}
The log is showing Null for _groupArray. I even tried using insertObjectAtIndex even that does not work.Not sure what I am doing wrong and yes I am getting the keys in the dictionary (_groups) nothing wrong with that.
You should initialize the array before starting to add values to it. Otherwise it is initially nil and will remain nil.
You can use allKeys to get all the keys of the array. But since _groupArray is an NSMutableArray, you have to do that like this:
_groupArray = [NSMutableArray arrayWithArray:[_groups allKeys]];
Or:
_groupArray = [[_groups allKeys] mutableCopy];
If _groupsArray is new or empty anyway then you can use
_gropusArray = [NSMutableArray arrayWithArray:[dict allKeys]];
That should release you from the compiler warning.
If _groupsArray was not empty before and you need to addValues then go for:
[_groupsArray addObjectsFromArray:[dict allKeys]];
this is how you should do it....
_groupsArray=[dict allKeys];
don't forget to allocate memory to your _groupsArray.. :)
Have you checked you've alloc'd and init'd your mutable array. Unless there's already stuff in it that you're adding to - and even then - consider using the NSDictiomary allKeys method rather than iterating through the dictionary.
From the docs
allKeys
Returns a new array containing the dictionary’s keys.
- (NSArray *) allKeys
Return Value
A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.
Discussion
The order of the elements in the array is not defined.

Sort One Dictionary with Another iPhone

I have two NSMutableDictionary objects. Dict 1 has fewer keys than dict 2, but the keys that both dictionaries share are identical in syntax. I'd like to re-sort dict 1 by the values for those keys in dict 2. The values in Dict 2 are integers.
Can someone get me started?
EDIT:
I have one array of keys and a dictionary with keys and numerical values. There are more keys and values in the dictionary than keys/objects in the array. I would like to re-order the array by the corresponding values of those keys from the dictionary.
Sorry for the redo on the question, but this more accurate.
Are you looking for the method call sortedArrayUsingComparator:? This will take one array and return you an array with the elements sorted.
Here's some sample code which sorts dictionaries based on a value in the field "sort order". You should read the documentation on these calls:
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) {
if ([[obj1 objectForKey:#"sortorder"] intValue] > [[obj2 objectForKey:#"sortorder"] intValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([[obj1 objectForKey:#"sortorder"] intValue] < [[obj2 objectForKey:#"sortorder"] intValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
+ (NSArray *) returnSortedArrayByAlpha:(NSArray*) inputArray whichField:(NSString*) whichField {
NSArray * sortedArray = [inputArray sortedArrayUsingComparator:sortBlock];
return sortedArray;
}
You might have a fundamental misunderstanding here. NSDictionary and NSSet objects are always unsorted.
Only NSArray and NSOrderedSet objects are sorted.
What you probably want to do is create a third object, an NSArray and populate it with whatever keys you want.
Then if you iterate through the NSArray, you can access the dictionary object in order of the sorted array.

How to search through a NSMutableArray

I have a NSMutableArray that I need to search for a string and return the key in the array where the string was found. So for example if I'm searching "ipod" and it's the 4th in the array, it would return 3 or whatever position the string is in. What's the best way to do this?
return [theArray indexOfObject:#"ipod"];
Reference: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/indexOfObject:.
Note that NSMutableArray inherits from NSArray, so any NSArray methods can be used on NSMutableArray too.
Again from the documentation:
Index of Object Passing test
You'll have to write a code block that tests for the substring in each object: NSString rangeOfString: options:
Then you'll get the index of the object with the substring. You'll need to run the string search again for your result, but that should get you what you are after.

NSDictionary with key => String and Value => c-Style array

I need an NSDictionary which has key in the form of string (#"key1", #"key2") and value in the form of a C-style two-dimensional array (valueArray1,valueArray2) where valueArray1 is defined as :
int valueArray1[8][3] = { {25,10,65},{50,30,75},{60,45,80},{75,60,10},
{10,70,80},{90,30,80},{20,15,90},{20,20,15} };
And same for valueArray2.
My aim is given an NSString i need to fetch the corresponding two-dimensional array.
I guess using an NSArray, instead of c-style array, will work but then i cannot initialize the arrays as done above (i have many such arrays). If, however, that is doable please let me know how.
Currently the following is giving a warning "Passing argument 1 of 'dictionaryWithObjectsAndKeys:' from incompatible pointer type" :
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:valueArray1,#"key1",
valueArray2,#"key2",nil];
Is valueArray2 also an int[][3]? If so, you could use
[NSValue valueWithPointer:valueArray1]
to convert the array into an ObjC value. To retrieve the content, you need to use
void* valuePtr = [[myDict objectForKey:#"key1"] pointerValue];
int(*valueArr)[3] = valuePtr;
// use valueArr as valueArrayX.
If there's just 2 keys, it is more efficient to use a function like
int(*getMyValueArr(NSString* key))[3] {
if ([key isEqualToString:#"key1"]) return valueArray1;
else return valueArray2;
}
Rather than Adding Array Directly as a value in NSDictionary make a custom class in which create variable of NSArray ... and set this class object as value like
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:MyClassObj1,#"key1",
MyClassObj2,#"key2",nil];
where MyClassObj1 and MyClassObj2 are member of MyClass

IPHONE: searching for a value in a sub dictionary inside a Dictionary

I have a dictionary of dictionaries and I have retrieved from a plist.
Suppose the high hierarchy dictionary is COUNTRIES and each sub dictionary is a COUNTRY.
Each COUNTRY sub dictionary has keys like name, currency, population, flag, etc.
After retrieving the dictionary and its subs to a variable as in
NSMutableDictionary * countries = [NSMutableDictionary dictionaryWithContentsOfFile:path];
How do I check to see if a currency named "euros" is present there?
I mean, I am checking for a value in a key of a subdictionary... is it possible? How?
thanks in advance.
NOTE: It is a dictionary inside a dictionary, not an array inside a dictionary or a dictionary inside an array. Each sub dictionary is store inside the main dictionary using a number. So, inside sub dictionary #1 may be a dictionary which keys are, for example, France, euros, 30 million people.
I need to see if France sub dictionary is present inside the main dictionary.
Use this to get any countries with a currency named "Euro" (in an NSArray).
NSArray *allCountries = [countries allValues];
NSPredicate *euroPredicate = [NSPredicate predicateWithFormat:#"currency == %#", #"Euro"];
NSArray *filteredCountries = [allCountries filteredArrayWithPredicate:euroPredicate];
If all you need to do is check whether such a country exists, then you can just do a simple if (filteredCountries.count > 0) { }.
Sidenote: I don't see a reason for the top data structure to be an NSDictionary if the country name is also stored in the inner NSDictionary (presumably the country name is the outer dictionary key) - perhaps an NSArray as the outer structure would be more appropriate?
NSDictionary *_currencyDict = [countries objectForKey:#"currency"];
NSArray *_currencies = [_currencyDict allValues];
NSPredicate *_currencyPredicate = [NSPredicate predicateWithFormat:#"SELF IN %#", _currencies];
BOOL _eurosResult = [_currencyPredicate evaluateWithObject:#"euros"];
if (_eurosResult)
NSLog(#"The value 'euros' is in the 'currency' dictionary, within the 'countries' dictionary.");
else
NSLog(#"The value 'euros' was not found.");