What is use of performSelector in iOS

前端 未结 5 1160
不知归路
不知归路 2021-02-15 23:55

What is the role of performSelector?

Comparing:

[self btnClicked];

and

[self performSelector:@selector(btn         


        
5条回答
  •  春和景丽
    2021-02-16 00:16

    A selector object lets you call a method that you do not know at compile time. You need to know only the name of a method as a string in order to call it.

    When the name of the method that you are calling is known at compile time, using selectors is counterproductive: the code becomes less readable for no apparent advantage. When you are writing a library that needs to call methods in other code that is compiled separately from the library, selectors provide a way to decouple the two pieces of code.

    For example, if you are writing a timer class that can call you back when a time interval is over, your timer does not know the name of the function that it needs to call, so it cannot write something like this:

    // We do not know if the function is called intervalHasExpired or something else
    [target intervalHasExpired];
    

    But if you give your timer a selector, the timer would be able to call you back.

    [myTimer scheduleWithTarget:self andSelector:@selector(myCompletion)];
    

提交回复
热议问题