Trying to iterate through an Array by checking against keys and objects of an NSDictionary in iOS [closed]

StackOverflow https://stackoverflow.com/questions/21341164

문제

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;
     }
 }
도움이 되었습니까?

해결책 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...

다른 팁

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];
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top