0

我正在为 iOS > 5.0 开发一个应用程序并使用 Xcode 4.6.2 并且我有一个UIView包含一堆UIKit元素的应用程序。

举个例子,我有一个自定义类,叫做RadioButton它的基类,UIButton就像你想象的那样。我还有一个名为CRTLabel的类,它是UILabel.

当我po [view subviews]在控制台时,我得到了

$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>>
)

我有 for 循环遍历视图的所有子视图。所以我使用这个代码,

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
}

我的应用程序崩溃了,说没有选定的属性。我用isKindOfClass方法来测试 radioButton 是一种RadioButton. 所以,我发现它会迭代所有的子视图,如果它不是RadioButton. 为了解释更多,即使当前子视图是 a CRTLabel,它也会跳过下一行,CRTLabel没有调用属性selected,所以它崩溃了。

所以,我的期望是消除所有不是的类,RadioButton它只迭代RadioButtons 上迭代。

所以我的问题是what is the advantage of specifying a custom class in foreach loop in Objective-c?我总是可以id在循环中使用而不是检查 id 是否是RadioButton.

4

2 回答 2

0

isKindOfClass在分配之前进行测试

for(id radioButton in view.subviews)
{
    if(radioButton isKindOfClass: RADIOBUTTON)
    { 

     if((RADIOBUTTON *)radioButton.selected == YES && (RADIOBUTTON *)radioButton.tag == 0)
     // Does something
     else if((RADIOBUTTON *)radioButton.selected == YES && (RADIOBUTTON *)radioButton.tag == 1)
     // Does something
    }
}
于 2013-05-24T10:58:18.230 回答
0

view.subviews将返回一个数组子视图。它将包括您的单选按钮、标签等任何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
      }
  }

您不能仅遍历特定视图(单选按钮)。正如您所说,您可以遍历所有视图并用于isKindOfClass识别特定的子视图。否则,您应该中继视图的标记属性以消除迭代

于 2013-05-24T11:00:17.457 回答