【问题标题】:Objective-C passing methods as parametersObjective-C 将方法作为参数传递
【发布时间】:2011-10-29 01:50:30
【问题描述】:

如何将一种方法作为参数传递给另一种方法?我正在跨班级这样做。

A类:

+ (void)theBigFunction:(?)func{
    // run the func here
}

B类:

- (void)littleBFunction {
    NSLog(@"classB little function");
}

// somewhere else in the class
[ClassA theBigFunction:littleBFunction]

C类:

- (void)littleCFunction {
    NSLog(@"classC little function");
}

// somewhere else in the class
[ClassA theBigFunction:littleCFunction]

【问题讨论】:

标签: iphone objective-c ios xcode selector


【解决方案1】:

您要查找的类型是选择器 (SEL),您会得到一个方法的选择器,如下所示:

SEL littleSelector = @selector(littleMethod);

如果方法接受参数,你只需将: 放在它们所在的位置,如下所示:

SEL littleSelector = @selector(littleMethodWithSomething:andSomethingElse:);

此外,方法并不是真正的函数,它们用于将消息发送到特定类(以 + 开头)或它的特定实例(以 - 开头)。函数是 C 类型,并没有像方法那样真正具有“目标”。

一旦获得选择器,就可以像这样在目标(无论是类还是实例)上调用该方法:

[target performSelector:someSelector];

这方面的一个很好的例子是UIControladdTarget:action:forControlEvents: 方法,您通常在以编程方式创建UIButton 或其他一些控件对象时使用。

【讨论】:

  • 你知道函数传入后我会如何调用它吗?我怀疑 [self func] 会起作用。
  • [目标 performSelector:someSelector];
【解决方案2】:

另一种选择是查看块。它允许您传递一段代码(闭包)。

这里有一篇很好的关于区块的文章:

http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1

这是苹果文档:

http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

【讨论】:

  • 这应该是被接受的答案,因为它更加通用。它还简化了将参数传递给被调用方法的情况取决于上下文。
【解决方案3】:

Objective C 使这个操作相对容易。苹果提供this documentation

要直接解决您的问题,您不是调用函数,而是调用选择器。下面是一些示例代码:

大功能:

+ (void)theBigFunction:(SEL)func fromObject:(id) object{
    [object preformSelector:func]
}

那么对于B类:

- (void)littleBFunction {
    NSLog(@"classB little function");
}

// somewhere else in the class
[ClassA theBigFunction:@selector(littleBFunction) fromObject:self]

那么对于C类:

- (void)littleCFunction {
    NSLog(@"classC little function");
}

// somewhere else in the class
[ClassA theBigFunction:@selector(littleCFunction) fromObject:self]

编辑:修复发送的选择器(删除分号)

【讨论】:

  • 您的选择器与方法描述不匹配,它们的末尾不应有任何:
  • 糟糕,很抱歉。我不是一个客观的 c 编码器(我只是涉足过它),而且我过于关注 Apple 的例子!
【解决方案4】:
猜你喜欢
  • 2023-03-13
  • 2014-07-14
  • 2011-09-13
  • 2018-09-09
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
相关资源
最近更新 更多