我尝试将myClass对象分配给UIView
类对象并使用myClass变量。
所以,
我创建了包含单位分段控制的myClass
@interface myClass : UIView
@property (nonatomic,readonly) UISegmentedControl *units;
在我的UIViewController
中,我尝试做类似的事情
myClass *newObject = [[myClass alloc]init];
UIView *newView;
newView = newObject;
[[newView units] addTarget:self action:@selector(changeUnit)
forControlEvents: UIControlEventValueChanged];
我收到“@interface
UIView
宣布selector
'单位'”
是否可以不使用myClass *newView = [[myClass alloc]init];
对象?
答案 0 :(得分:2)
好吧,多亏了Objective-C的灵活性,尽管这是一个奇怪的要求,但你可以做你想要的事情。
这行代码:[[newView units] addTarget:...]
不应生成任何编译器错误(除非您将“将警告视为错误”标记为YES),但它会生成警告。只要newView
变量实际上是myClass
的实例,一切都将按预期工作。
您可以采取一些预防措施,例如使用respondsToSelector:
和isKindOfClass:
方法。这是一种可以使代码更加健壮的方法:
myClass *newObject = [[myClass alloc] init];
UIView *newView = nil; // always initialize method variables to nil
newView = newObject;
// make sure 'newView' can respond to the 'units' selector
if ( [newView respondsToSelector:@selector(units)] )
{
// if it does, use 'performSelector' instead of calling the method
// directly to avoid a compiler warning
id unitsObject = [newView performSelector:@selector(units)];
// make sure the object returned by 'performSelector' is actually
// a UISegmentedControl
if ( [unitsObject isKindOfClass:[UISegmentedControl class]] )
{
// if it is, cast it...
UISegmentedControl *units = (UISegmentedControl*)unitsObject;
// ... and add the Target-Action to it
[units addTarget:self action:@selector(changeUnit)
forControlEvents: UIControlEventValueChanged];
}
}
记住
希望这有帮助!
答案 1 :(得分:1)
这是OOP的基础知识。您的newView
是UIView
,没有units
。
您的子类myClass
有units
。
只需使用[[newObject units] addTarget...(etc)]
。