我尝试将 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];
我收到“UIView
没有可见的@interface
声明选择器
‘单位’”
是否可以不使用 myClass *newView = [[myClass alloc]init];
对象?
最佳答案
好吧,由于 Objective-C 的灵 active ,尽管这是一个奇怪的要求,但可以执行您的要求。
这行代码:[[newView units] addTarget:...]
不应生成任何编译器错误(除非您已将“Treat Warnings as Errors”标志设置为 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];
}
}
记住
- 正确初始化“myClass”中的“units”属性或在使用前正确分配它
- 当您实例化“newObject”变量时,您调用的是“init”而不是默认的初始化程序“initWithRect:”。确保这是预期的行为。
希望这对您有所帮助!
关于iphone - 将 myClass 对象分配给 UIView 对象并使用 myClass 选择器(变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19389756/