Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List selectors for Objective-C object

I have an object, and I want to list all the selectors to which it responds. It feels like this should be perfectly possible, but I'm having trouble finding the APIs.

like image 337
Airsource Ltd Avatar asked Dec 01 '08 04:12

Airsource Ltd


People also ask

What are selectors Objective-C?

In Objective-C, selector has two meanings. It can be used to refer simply to the name of a method when it's used in a source-code message to an object. It also, though, refers to the unique identifier that replaces the name when the source code is compiled.

How do I find the class of an object in Objective-C?

[yourObject isKindOfClass:[a class]] // Returns a Boolean value that indicates whether the receiver is an instance of // given class or an instance of any class that inherits from that class.

What are selectors in Swift?

Use Selectors to Arrange Calls to Objective-C Methods In Objective-C, a selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector structure, and you create them using the #selector expression.


2 Answers

This is a solution based on the runtime C functions:

class_copyMethodList returns a list of class methods given a Class object obtainable from an object.

#import <objc/runtime.h> 

[..]

SomeClass * t = [[SomeClass alloc] init];  int i=0; unsigned int mc = 0; Method * mlist = class_copyMethodList(object_getClass(t), &mc); NSLog(@"%d methods", mc); for(i=0;i<mc;i++)     NSLog(@"Method no #%d: %s", i, sel_getName(method_getName(mlist[i])));  /* note mlist needs to be freed */ 
like image 56
diciu Avatar answered Sep 21 '22 03:09

diciu


I think usually you'll want to do that in the console, instead of cluttering your code with debug code. This is how you can do that while debugging in lldb:

(Assuming an object t)

p int $num = 0; expr Method *$m = (Method *)class_copyMethodList((Class)object_getClass(t), &$num); expr for(int i=0;i<$num;i++) { (void)NSLog(@"%s",(char *)sel_getName((SEL)method_getName($m[i]))); } 
like image 43
José Manuel Sánchez Avatar answered Sep 21 '22 03:09

José Manuel Sánchez