Cocoa:在Objective-C中实现目标 - 动作模式,并接收发送到实例的' NSInvalidArgumentException无法识别的选择器'

时间:2015-01-23 20:03:34

标签: ios objective-c cocoa-touch cocoa-design-patterns

我正在尝试在自定义UIControl中实现目标操作模式。这是设置:

// Inside custom UIControl class

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    ...

    // UIControl method to update targets when values change
    [self sendActionsForControlEvents:UIControlEventValueChanged];

    return YES;
}

- (void)valueChanged:(id)control
{
    NSLog(@"Value changed");
}

我有一个简单的视图控制器,它初始化我的自定义UIControl的一个实例,并在值发生变化时注册为目标:

// Inside view controller

@implementation HKViewController
{
    HKCustomControl *_customControl;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _customControl = [[HKCustomControl alloc]];

    [self.view addSubview:_customControl];

    [_customControl addTarget:self
                action:@selector(valueChanged:)
      forControlEvents:UIControlEventValueChanged];
}

我得到的错误是:''NSInvalidArgumentException',原因:' - [HKViewController valueChanged:]:无法识别的选择器发送到实例0x16d95b20'

我已将- (void)valueChange:(id)control添加到我的自定义控件的.h文件中。

我已经阅读了很多关于类似错误的帖子,但没有特定于此模式。我可以用第二双眼睛看看我哪里出错了。

2 个答案:

答案 0 :(得分:0)

根据您的以下声明,

action被发送到addTarget中指定的对象self

[_customControl addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];

因此,您需要将valueChanged添加到控制器类对象。

答案 1 :(得分:0)

答案由@rmaddy提供:我需要在视图控制器中使用valueChanged:方法而不是类