将myClass对象分配给UIView对象并使用myClass选择器(变量)

时间:2013-10-15 19:47:57

标签: iphone ios objective-c uiview

我尝试将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];对象?

2 个答案:

答案 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];
    }
}

记住

  • 正确初始化'myClass'中的'units'属性或在使用之前正确分配它
  • 当你实例化'newObject'变量时,你正在调用'init'而不是默认的initalizer'initWithRect:'。确保这是预期的行为。

希望这有帮助!

答案 1 :(得分:1)

这是OOP的基础知识。您的newViewUIView,没有units

您的子类myClassunits

只需使用[[newObject units] addTarget...(etc)]