Objective-C作为参数传递的方法

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]

1
你传递选择器,这里有一个类似的问题:https://dev59.com/MnRB5IYBdhLWcg3wxZ7Y - utahwithak
4个回答

49
你要找的类型是选择器(SEL),你可以通过以下方式获取方法的选择器:
SEL littleSelector = @selector(littleMethod);

如果方法需要参数,只需在对应位置放置:,像这样:

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

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

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

[target performSelector:someSelector];

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


你知道我在传递函数后该如何调用它吗?我怀疑 [self func] 能否正常工作。 - Jacksonkr
3
[target performSelector:someSelector]; - Filip Radelic

9

这应该是被接受的答案,因为它更加通用。它还简化了传递参数到被调用方法取决于上下文的情况。 - aclima

7

Objective C使得这个操作相对容易。苹果提供了这份文档

直接回答您的问题,您不是在调用函数,而是在调用选择器。以下是一些示例代码:

大函数:

+ (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]

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


你的选择器与方法描述不匹配,它们末尾不应该有任何“:”。 - Filip Radelic
抱歉,我并不是一个很擅长Objective C编程的人(只是涉猎一下),而且我盲目地跟随了苹果的例子! - MJD


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接