Objective-C passing methods as parameters

前端 未结 2 700
小蘑菇
小蘑菇 2021-02-11 18:04

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

Class A:

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


        
2条回答
  •  名媛妹妹
    2021-02-11 18:37

    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:);
    

    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];
    

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

提交回复
热议问题