Получить все методы класса или экземпляра Objective-C - PullRequest
35 голосов
/ 19 января 2010

В Objective-C я могу проверить, отвечает ли данный класс или экземпляр определенным селекторам. Но как запросить класс или экземпляр для всех его методов или свойств класса (например, список всех методов или свойств)?

Ответы [ 4 ]

39 голосов
/ 22 ноября 2014

Вы можете сделать это, и это очень хорошо задокументировано на https://developer.apple.com/library/mac/documentation/cocoa/Reference/ObjCRuntimeRef/index.html

Чтобы получить все методы экземпляра или класса класса, вы можете использовать class_copyMethodList и перебрать результаты. Пример:

 #import <objc/runtime.h>

/**
 *  Gets a list of all methods on a class (or metaclass)
 *  and dumps some properties of each
 *
 *  @param clz the class or metaclass to investigate
 */
void DumpObjcMethods(Class clz) {

    unsigned int methodCount = 0;
    Method *methods = class_copyMethodList(clz, &methodCount);

    printf("Found %d methods on '%s'\n", methodCount, class_getName(clz));

    for (unsigned int i = 0; i < methodCount; i++) {
        Method method = methods[i];

        printf("\t'%s' has method named '%s' of encoding '%s'\n",
               class_getName(clz),
               sel_getName(method_getName(method)),
               method_getTypeEncoding(method));

        /**
         *  Or do whatever you need here...
         */
    }

    free(methods);
}

Вам нужно будет сделать два отдельных вызова этого метода. Один для методов экземпляра, а другой для методов класса:

/**
 *  This will dump all the instance methods
 */
DumpObjcMethods(yourClass);

Вызов этого же метакласса даст вам все методы класса

/**
 *  Calling the same on the metaclass gives you
 *  the class methods
 */
DumpObjcMethods(object_getClass(yourClass) /* Metaclass */);
37 голосов
/ 21 июля 2016

В дополнение к ответу Баззи для отладки вы можете использовать приватный метод -[NSObject _methodDescription].

Либо в lldb:

(lldb) po [[UIApplication sharedApplication] _methodDescription]

или в коде:

@interface NSObject (Private)
- (NSString*)_methodDescription;
@end

// Somewhere in the code:
NSLog(@"%@", [objectToInspect performSelector:@selector(_methodDescription)]);

Вывод будет выглядеть следующим образом:

<__NSArrayM: 0x7f9 ddc4359a0>:
in __NSArrayM:
    Class Methods:
        + (BOOL) automaticallyNotifiesObserversForKey:(id)arg1; (0x11503b510)
        + (id) allocWithZone:(_NSZone*)arg1; (0x11503b520)
        + (id) __new:::::(const id*)arg1; (0x114f0d700)
    Instance Methods:
        - (void) removeLastObject; (0x114f669a0)
        - (void) dealloc; (0x114f2a8f0)
        - (void) finalize; (0x11503b2c0)
        - (id) copyWithZone:(_NSZone*)arg1; (0x114f35500)
        - (unsigned long) count; (0x114f0d920)
        - (id) objectAtIndex:(unsigned long)arg1; (0x114f2a730)
        - (void) getObjects:(id*)arg1 range:(_NSRange)arg2; (0x114f35650)
        - (void) addObject:(id)arg1; (0x114f0d8e0)
        - (void) setObject:(id)arg1 atIndex:(unsigned long)arg2; (0x114f99680)
        - (void) insertObject:(id)arg1 atIndex:(unsigned long)arg2; (0x114f0d940)
        - (void) exchangeObjectAtIndex:(unsigned long)arg1 withObjectAtIndex:(unsigned long)arg2; (0x114f8bf80)
        ......
in NSMutableArray:
    Class Methods:
        + (id) copyNonRetainingArray; (0x11ee20178)
        + (id) nonRetainingArray; (0x11ee201e8)
        + (id) nonRetainingArray; (0x120475026)
        + (id) arrayWithCapacity:(unsigned long)arg1; (0x114f74280)
        ......
9 голосов
/ 19 января 2010

Вы захотите использовать методы времени выполнения Objective C, см. Здесь: https://developer.apple.com/reference/objectivec/objective_c_runtime

4 голосов
/ 19 января 2010

Это возможно через objc_method_list.Для того, чтобы перечислить ваши методы, вам придется зарегистрировать все ваши методы заранее.

Процесс прост: после того, как вы объявили свою функцию, вы можете создать экземпляр objc_method и зарегистрировать имя функции.Затем добавьте objc_method в список objc_method_list и, наконец, передайте список objc_method_list в class_addMethods.

...