How to implement or modify a method submission table in Objective-C?

It is sometimes useful to set up a method dispatch table, so calling A calls AImpl (), and calling A at other times calls BImpl (). How can this be done in Objective-C for a method that is automatically called by the system (for example, delegate methods)?

For example, if sytem calls viewDidAppear for the first time, I want it to call viewAppearFirstTime, while calling viewDidAppear subsequently gets into a completely different method (instead of checking if-else inside the code using a boolean flag).

Another example: UIView drawRect is called very often in the application, if the drawRect called for the first time is different from the subsequent ones, I don’t want to include if-test, because the code is harder to read and the check is also not needed after the first time.

+3
source share
4 answers

I cautioned here: the specific case that you are describing should probably not be done that way. This is almost certainly too clever and should probably be divided into viewDidLoadand viewWillAppearnot two versions viewWillAppear. However, a problem arose.

My preferred solution for this is to save SEL, which indicates what I want to do. For example, I use this technique for the “next step” after complex asynchronous activity:

if (self.nextActionSelector != NULL)
{
    [self performSelector:self.nextActionSelector];
}

, viewWillAppearSelector, , viewWillAppear , .

Ben Method Method Swizzling , , - , . ... , . . .

, -forwardInvocation:, , . , , . , , . . , , , , .

, , , . , view - , , , , (, iPhone , ). , , , , - . , , NSInvocation - (, , , 500 , . , , ).

+3

this, NSInvocation NSDictionary.

+2

Objective-C , . CocoaDev : CocoaDev: Swizzling. , , , obj-c.

, , NSInvocations. viewDidAppear viewAppearFirstTime: , swizzling, , .

!

+2

, swizzling. , , , , class_replaceMethod viewDidAppearFirstTime.

However, if you want to change the method sending for one instance, I think that your only option is a conditional expression in your method viewDidAppearor to consider a redesign that does not require separate methods at the first and subsequent appearances (from your description, dividing your code into functions viewDidLoadand viewWillAppearseems to make sense).

+2
source

Source: https://habr.com/ru/post/1710497/


All Articles