【问题标题】:Is there a special way to declare methods that need to be known about but not actually used within the class they're declared in?是否有一种特殊的方法来声明需要知道但在声明它们的类中没有实际使用的方法?
【发布时间】:2014-05-03 22:19:35
【问题描述】:

此按钮在我的基类中声明:

{
    // Setup done button for tool bar
    UIButton *doneButton = [[UIButton alloc] initWithFrame:CGRectMake(170, 3, 110, 38)];
    [doneButton setBackgroundColor:[UIColor blackColor]];
    [doneButton setTitle:@"Done" forState:UIControlStateNormal];
    [doneButton addTarget:_thisController action:@selector(doneButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    return doneButton;
}

注意这一行:

[doneButton addTarget:_thisController action:@selector(doneButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

“doneButtonTapped:”方法只在我的基类的每个子类中使用,从不在基类本身中使用。

为了避免在基类中出现警告,我至少必须定义方法:

- (void)doneButtonTapped:(id)sender {
}

问题:

有没有办法避免声明空方法而不收到警告?

像上面这样的空白方法有问题吗?

我知道我可以为每个子类中的选择器添加目标,但其中有很多。我只是认为将所有内容都留在 doneButtonTapped 方法中会更容易。

【问题讨论】:

  • 这根本不是问题。在文档中写下 sublcas 必须实现此方法并在标题中声明它。您可以将公共代码放在此基类中的所有子类中,并要求在子类实现中调用 [super doneButtonTapped:sender],就像使用 [super viewDidLoad]
  • 也可能让基方法抛出一些异常,以处理子类不遵守约定并实现它的情况。
  • @jordan 好主意,如果不调用超级实现

标签: ios objective-c cocoa-touch uiviewcontroller nsobject


【解决方案1】:

有办法;):

NSString *stringMethod = @"doneButtonTapped:";
[doneButton addTarget:self action:NSSelectorFromString(stringMethod) forControlEvents:UIControlEventTouchUpInside];

通过这种方式,您还可以在创建按钮之前在运行时更改您的方法,只需更改字符串即可。而且这样的警告,不会在预编译时显示出来。

所以,尽情享受吧! ;)

【讨论】:

  • 完美,不知道存在。
  • 记住:曾经有一个函数可以将字符串带入其他东西 :devil: ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 2023-02-20
相关资源
最近更新 更多