Using [self method] or @selector (method)?

Can anyone enlighten me regarding the differences between the two statements below.

[self playButtonSound]; 

and

 [self performSelector:@selector(playButtonSound)]; 

I am just asking how I had the old code that @selector used, now with a little knowledge, I can’t think why I didn’t use [self playButtonSound] instead, they both seem to do the same thing as here.

Gary

+10
objective-c iphone cocoa-touch
Apr 20 2018-10-11T00:
source share
2 answers

And the same thing, but [self playButtonSound]; Undoubtedly, this is the usual way to call a method in Objective-C. However, using performSelector: allows you to call a method that is defined only at run time.

From the NSObject Protocol Link :

The performSelector method: is equivalent to sending aSelector message directly to the recipient. For example, all three of the following messages do the same:

 id myClone = [anObject copy]; id myClone = [anObject performSelector:@selector(copy)]; id myClone = [anObject performSelector:sel_getUid("copy")]; 

However, the performSelector: method allows you to send messages that arent determined before runtime. a variable selector can be passed as an argument:

 SEL myMethod = findTheAppropriateSelectorForTheCurrentSituation(); [anObject performSelector:myMethod]; 
+10
Apr 20 '10 at 12:01
source share
 [self playButtonSound]; 

Here, the compiler checks to see if your object responds to the -playButtonSound message and will give you a warning if this is not the case.

 [self performSelector:@selector(playButtonSound)]; 

Calling -playButtonSound this way you will not get a compiler warning. However, you can dynamically check whether objects respond to a specific selector, so you can safely try to call an arbitrary selector of an object without specifying its type and not receive warnings about the compiler (which can be useful, for example, for calling additional methods in object deletes)

 if ([self respondsToSelector:@selector(playButtonSound)]) [self performSelector:@selector(playButtonSound)]; 
+6
Apr 20 2018-10-12T00:
source share



All Articles