0

I've been using the following to create an array from a plist of dictionaries:

self.cough = [NSMutableArray arrayWithCapacity:[ailments count]];
NSDictionary* dict;
for (dict in ailments)
    if ([[dict valueForKey:@"section"]isEqualToString:@"coughing"])[cough addObject:dict];

The format of the plist is:

section:    coughing
name:       Common Cold

The trouble I'm having, and I suspect its an easy one is, if I want to have "Common Cold" in a different section, like "Headache", I could create another ailment object for the new section but it messes up my search result by showing 2 Common Cold entries (from both "Coughing" and "Headache").

What I'd like to do is:

section:    coughing, headache
name:       Common Cold

What would I use instead of isEqualToString: to create two different arrays, one for "Coughing" and another for "Headache"?

awDemo
  • 355
  • 1
  • 5
  • 14

2 Answers2

0

It appears that you are manually checking against for section type. If you wanted to continue this way, all you really need to do is check and see if the section string contains the substring of the particular section you're evaluating for:

How do I check if a string contains another string in Objective-C?

However rather than statically define what section names you're looking for, it might benefit you to consider trying to obtain sections names/types dynamically from your plist and then sorting into those sections.

Community
  • 1
  • 1
isaac
  • 4,867
  • 1
  • 21
  • 31
  • Thanks isaac. How would I dynamically obtain sections, rather than statically? I think I follow but need a little guidance here... – awDemo Nov 06 '11 at 22:24
  • Ok. Although isaac is correct that I should dynamically obtain sections names/types, I found a way to do it based on my original question... instead of `isEqualToString`, I can use `if ([[dict valueForKey:@"section"]rangeOfString:@"coughing"].location !=NSNotFound)[cough addObject:dict];` It's static but it works. isaac's answer is correct since I found my answer. – awDemo Nov 06 '11 at 22:46
0
NSMutableDictionary *ailmentsBySection = [NSMutableDictionary dictionary];
[ailmentsBySection addObject:[NSMutableArray array] forKey:@"coughing"];
[ailmentsBySection addObject:[NSMutableArray array] forKey:@"headache"];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
for (NSDictionary *ailment in ailments) {
    NSString *sections = [ailment objectForKey:@"section"];
    for (NSString *section in [sections componentsSeparatedByString:@","]) {
        section = [section stringByTrimmingCharactersInSet:whitespace];
        [[ailmentsBySection objectForKey:section] addObject:ailment];
    }
}

Note that it's legal to send any message to nil, so it's ok if section ends up being something other than coughing or headache. On the other hand you could also dynamically add new keys to ailmentsBySection as you find them instead of just allowing coughing and headache.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848