C传递方法作为参数

C传递方法作为参数

本文介绍了Objective-C传递方法作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一个方法作为参数传递给另一个方法?我在课堂上这样做。

How do you pass one method as a parameter to another method? I'm doing this across classes.

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]


推荐答案

你要找的类型是选择器( SEL ),你得到一个方法的选择器这个:

The type you are looking for is selector (SEL) and you get a method's selector like this:

SEL littleSelector = @selector(littleMethod);

如果方法采用参数,你只需输入他们去哪里,像这样:

If the method takes parameters, you just put : where they go, like this:

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

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

Also, methods are not really functions, they are used to send messages to specific class (when starting with +) or specific instance of it (when starting with -). Functions are C-type that doesn't really have a "target" like methods do.

一旦你得到一个选择器,你就可以在你的目标上调用该方法(无论如何)类或实例)像这样:

Once you get a selector, you call that method on your target (be it class or instance) like this:

[target performSelector:someSelector];

一个很好的例子是 UIControl ' s 通常在以编程方式创建 UIButton 或其他控件对象时使用的方法。

A good example of this is UIControl's addTarget:action:forControlEvents: method you usually use when creating UIButton or some other control objects programmatically.

这篇关于Objective-C传递方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:54