Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a specific string from an NSMutableArray using NSDictionary

I'm learning iphone app development and working on something that allows you to enter two words and combines them. The two words and the combined word are entered into a dictionary and that is then stored in a mutable array. There is another option that allows you to enter an entire word and if it is in the array, it will return the two separate words that make it. My problem is that I don't know how to search an array and go through each object and sort out the answer. For example:

(
    {
    "Combined Word" = snowman;
    "Word 1" = snow;
    "Word 2" = man;
},
    {
    "Combined Word" = dirtbike;
    "Word 1" = dirt;
    "Word 2" = bike;
},
    {
    "Combined Word" = schoolbus;
    "Word 1" = school;
    "Word 2" = bus;
},
    {
    "Combined Word" = raindrop;
    "Word 1" = rain;
    "Word 2" = drop;
}

if I enter schoolbus and press the button, how do I code so that the mutable array is searched and each object's "Combined Word" is analyzed so that is the word entered is a value, it will return the corresponding "Word 1" and "Word 2".


2 Answers

I dont know whether there are any better or efficient methods, but I may try something like this:

NSString* word1;
NSString* word2;
for(NSDictionary *dict in yourArray){
   if([[dict objectForKey:@"Combined Word"] isEqualToString:yourSearchWord]]){
       word1 = [dict objectForKey:@"Word 1"];
       word2 = [dict objectForKey:@"Word 2"]; 
   }
}

Please note that this is a typo and haven't checked in XCode.

like image 166
HRM Avatar answered Jun 26 '26 10:06

HRM


Use NSPredicate

NSString *value= @"value1";
NSPredicate *key1Predicate = [NSPredicate predicateWithFormat:@"%@ IN self.@allValues", value];
NSArray *filteretSet1 = [dataSet filteredArrayUsingPredicate:key1Predicate];
NSLog(@"filteretSet1: %@",filteretSet1);

Hope this will help you.

like image 42
Prashant Nikam Avatar answered Jun 26 '26 10:06

Prashant Nikam