Resolved How do I loop through a series of nested variables?

Discussion in 'iOS Programming' started by moonman239, Jun 18, 2014.

  1. moonman239 macrumors 68000

    Joined:
    Mar 27, 2009
    #1
    I was just about to ask, but I figured out the answer on my own.

    Suppose I have an NSDictionary, and some of its values are NSDictionaries themselves, and some of their values are NSDictionaries. If I want to loop through all of the dictionaries, I can simply create a category on NSDictionary that includes a method that is written like this:

    Code:
    -(void)doSomething
    {
    // some code here
    for (NSDictionary *dictionary in [self allValues])
    {
    [dictionary doSomething];
    }
    }
    
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    That code will only work if every value in self is an NSDictionary. It will fail if there are any other types.

    Since you did say "some of its values" rather than "all of its values", this suggests that some of its values won't be NSDictionary, and those will fail.

    You should look at isKindOfClass: in the NSObject protocol methods.
     
  3. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #3
    A debatably better solution would be to check if it responds to the selector you want to call.

    The downside is the possibility that you have multiple unrelated selectors that are called the same thing, then you're accidentally using a selector you didn't intend to use on an object that you failed to anticipate would be present.
     

Share This Page