我正在为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(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
的那种。要解释更多信息,即使当前子视图是CRTLabel
,它也会跳过下一行,CRTLabel
没有名为selected
的属性,因此崩溃。
所以,我的期望是消除所有不是RadioButton
的类,并且它只在RadioButton
s上进行迭代。
所以我的问题是what is the advantage of specifying a custom class in foreach loop in Objective-c
?我总是可以在循环中使用id
,而不是检查id是否属于RadioButton
。
答案 0 :(得分: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
}
}
答案 1 :(得分: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
}
}
您无法仅遍历特定视图(radioButton)。正如您所说,您可以遍历所有视图并使用isKindOfClass
来标识特定的子视图。否则,您应该转发视图的标记属性以消除迭代