【问题标题】:Cocoa: Implementing the target-action pattern in Objective-C and receiving 'NSInvalidArgumentException unrecognized selector sent to instance'Cocoa:在 Objective-C 中实现目标动作模式并接收'NSInvalidArgumentException unrecognized selector sent to instance'
【发布时间】:2015-01-24 09:16:03
【问题描述】:

我正在尝试在自定义 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:]: unrecognized selector sent to instance 0x16d95b20'

我还为我的自定义控件添加了- (void)valueChange:(id)control.h 文件。

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

【问题讨论】:

  • valueChanged: 需要在视图控制器类中,而不是控件类中。
  • 是的 - 你明白了。谢谢!

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    action 被发送到addTarget 中指定的对象,即self,根据您的以下声明:

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

    所以你需要将valueChanged 添加到控制器类对象中。

    【讨论】:

    • 你为什么要这样做?这意味着控件响应自己的更改。视图控制器需要知道更改。
    • @maddy 的想法是强调valueChanged: 应该在addTarget 中指定的类中定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多