美文网首页iOS
iOS 给父类发送消息

iOS 给父类发送消息

作者: 萧城x | 来源:发表于2017-01-10 15:37 被阅读66次

<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>

相关文章

网友评论

    本文标题:iOS 给父类发送消息

    本文链接:https://www.haomeiwen.com/subject/nmgkbttx.html