iOS 給父類傳送訊息

weixin_34087301發表於2017-01-10

<pre>

@interface NSObject (QMUI)

/**
對 super 傳送訊息

@param aSelector 要傳送的訊息
@return 訊息執行後的結果
@link http://stackoverflow.com/questions/14635024/using-objc-msgsendsuper-to-invoke-a-class-method
*/

  • (id)performSelectorToSuperclass:(SEL)aSelector;

/**
對 super 傳送訊息

@param aSelector 要傳送的訊息
@param object 作為引數傳過去
@return 訊息執行後的結果
@link http://stackoverflow.com/questions/14635024/using-objc-msgsendsuper-to-invoke-a-class-method
*/

  • (id)performSelectorToSuperclass:(SEL)aSelector withObject:(id)object;

/**
遍歷某個 protocol 裡的所有方法

@param protocol 要遍歷的 protocol,例如 @protocol(xxx)
@param block 遍歷過程中呼叫的 block
*/

  • (void)enumerateProtocolMethods:(Protocol *)protocol usingBlock:(void (^)(SEL selector))block;
    @end
    </pre>

<pre>
@implementation NSObject (QMUI)

  • (id)performSelectorToSuperclass:(SEL)aSelector {
    struct objc_super mySuper;
    mySuper.receiver = self;
    mySuper.super_class = class_getSuperclass(object_getClass(self));

    id (*objc_superAllocTyped)(struct objc_super *, SEL) = (void )&objc_msgSendSuper;
    return (
    objc_superAllocTyped)(&mySuper, aSelector);
    }

  • (id)performSelectorToSuperclass:(SEL)aSelector withObject:(id)object {
    struct objc_super mySuper;
    mySuper.receiver = self;
    mySuper.super_class = class_getSuperclass(object_getClass(self));

    id (*objc_superAllocTyped)(struct objc_super *, SEL, ...) = (void )&objc_msgSendSuper;
    return (
    objc_superAllocTyped)(&mySuper, aSelector, object);
    }

  • (void)enumerateProtocolMethods:(Protocol *)protocol usingBlock:(void (^)(SEL))block {
    unsigned int methodCount = 0;
    struct objc_method_description *methods = protocol_copyMethodDescriptionList(protocol, NO, YES, &methodCount);
    for (int i = 0; i < methodCount; i++) {
    struct objc_method_description methodDescription = methods[i];
    if (block) {
    block(methodDescription.name);
    }
    }
    free(methods);
    }

@end
</pre>

相關文章