Search code examples
iphoneiosios5ios6uikit

using id instead of custom class in for loop


I'm developing an app for iOS > 5.0 and using Xcode 4.6.2 & I've a UIView that contains a bunch of UIKit elements.

To give an example, i have a custom class called RadioButton whose base class is UIButton as you imagine. I've also a class called CRTLabel which is a subclass of UILabel.

When i po [view subviews] in the console , i got

$0 = 0x0754c4d0 <__NSArrayM 0x754c4d0>(
<CRTLabel: 0x857f120; baseClass = UILabel; frame = (10 10; 360 35); text = '2- Sizce evet mi hayır mı...'; clipsToBounds = YES; userInteractionEnabled = NO; tag = 1; layer = <CALayer: 0x857f1b0>>,
<RadioButton: 0x857f520; baseClass = UIButton; frame = (20 65; 44 44); opaque = NO; layer = <CALayer: 0x857f5e0>>,
<CRTLabel: 0x857f800; baseClass = UILabel; frame = (84 65; 600 44); text = 'Evet'; clipsToBounds = YES; userInteractionEnabled = NO; tag = 122; layer = <CALayer: 0x857f740>>,
<RadioButton: 0x857fb50; baseClass = UIButton; frame = (20 139; 44 44); opaque = NO; tag = 1; layer = <CALayer: 0x857fa60>>,
<CRTLabel: 0x857fd60; baseClass = UILabel; frame = (84 139; 600 44); text = 'Hayır'; clipsToBounds = YES; userInteractionEnabled = NO; tag = 122; layer = <CALayer: 0x857fc60>>
)

I've for loop to iterate over all of the subviews of view. So i use this code ,

for(RadioButton *radioButton in view.subviews)
{
     if(radioButton.selected == YES && radioButton.tag == 0)
     // Does something
     else if(radioButton.selected == YES && radioButton.tag == 1)
     // Does something
}

My app's crashed saying that there is no selected property. I've used isKindOfClass method to test radioButton is kind of RadioButton. So, i found that it iterates all the subviews if it's not kind of RadioButton. To explain more, even if current subview is a CRTLabel, it steps over the next line, CRTLabel doesn't have property called selected, so it crashes.

So, my expectation was to eliminate all of classes which isn't RadioButton and it iterates only over RadioButtons.

So my question is that what is the advantage of specifying a custom class in foreach loop in Objective-c ? I can always use id in loop than check if id is kind of RadioButton.


Solution

  • view.subviews will return an array sub views. It will include both your radio buttons, labels like anything which is the subview of view.

      for(RadioButton *radioButton in view.subviews) //  logically wrong since subView can be anything button,label...
    
      for(UIView *subView in view.subviews)
      { 
         // Iterate through all subViews
    
         if([subView isKindOfClass:[RadioButton class]])
          {
            //safe no crash
          }
      }
    

    You cannot iterate through specific views(radioButton) only. As you said you can iterate through all the views and use isKindOfClass to identify a specific subView. Otherwise you should relay on tag property of the view to eleminate the iteration