Is it possible to pass a method as an argument in Objective-C?

后端 未结 3 2163
说谎
说谎 2020-12-25 13:05

I have a method that varies by a single method call inside, and I\'d like to pass the method/signature of the method that it varies by as an argument... is this possible in

3条回答
  •  失恋的感觉
    2020-12-25 13:40

    As said before you can pass the selector of the method you want to call. Using a selector there are different ways to actually call the method:

    1. using NSObjects performSelector:, performSelector:withObject: and performSelector:withObject:withObject: methods
    2. using a NSInvocation object
    3. or directly using objc_msgSend or objc_msgSend_stret
    4. using the IMP of that method which you can get using methodForSelector:

    Which one to use really depends on the situation. If the performance is not critical I’d go ahead with 1 if you need to pass in 0, 1 or 2 objects. If the performSelector:... methods don’t match I’d go with 2 or 3. Since setting up an NSInvocation object requires a lot of boilerplate code I prefer 3, but I guess that’s a matter of personal choice, unless there are performance issues.

    If the performance of those method calls does matter I’d use 3 or 4. 3 should be faster unless you can cache the IMPs. But depending on your code this may not be feasible or doesn’t really help. So here you must profile the code and see which one is better for you.

提交回复
热议问题