Question

I have an NSArray of UISwitches. I have separately an NSDictionary whose keys are NSNumbers, and whose objects are BOOL values in the form of NSString objects. What I would like to do is iterate through the NSArray of UISwitches, check to see if the tag value is one of the keys inside the NSDictionary, and if a match is found, then set the enabled property of the UISwitch to the key's corresponding object (after converting it to a BOOL from an NSString).

My code is as follows:

for (int i=0; i<[self.switchCollection count]; i++) {
     UISwitch *mySwitch = (UISwitch *)[self.switchCollection objectAtIndex:i];
     if (tireSwitch.tag == //this has to match the key at index i) {
                    BOOL enabledValue = [[self.myDictionary objectForKey:[NSNumber numberWithInt://this is the key that is pulled from the line above]] boolValue];
                    mySwitch.enabled = enabledValue;
     }
 }
Was it helpful?

Solution 2

Your code doesn't look right. How about this:

(Edited to use fast enumeration (for...in loop syntax)

//Loop through the array of switches.
for (UISwitch *mySwitch  in self.switchCollection) 
{
     //Get the tag for this switch
  int tag = mySwitch.tag;

  //Try to fetch a string from the dictionary using the tag as a key
  NSNumber *key = @(tag);
  NSString *dictionaryValue = self.myDictionary[key];

  //If there is an entry in the dictionary for this tag, set the switch value.
  if (dictionaryValue != nil) 
  {
    BOOL enabledValue = [dictionaryValue boolValue];
    mySwitch.enabled = enabledValue;
  }
}

That's assuming I understand what you're trying to do...

OTHER TIPS

Now that Duncan C's answer has made clear what you're trying to accomplish, it can be written much more simply.

Iterate the array directly. You don't need i at all, since you're not using it to access anything other than the array.

For each switch, try to get a value from the dictionary using the tag (this is wrapped in an NSNumber using the @() boxing syntax.

If a value exists, then set the switch's enabled.

for( UISwitch * switch in self.switchCollection ){
    NSString * enabledVal = self.myDictionary[@(switch.tag)];
    if( enabledVal ){
        switch.enabled = [enabledVal boolValue];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top