Using Super in an Objective C Category?

后端 未结 3 1392
名媛妹妹
名媛妹妹 2020-12-05 02:44

I\'d like to override a method in an Objective C class that I don\'t have the source to.

I\'ve looked into it, and it appears that Categories should allow me to do t

3条回答
  •  青春惊慌失措
    2020-12-05 03:42

    Not exactly in category but there is a workaround by adding the method dynamically at runtime. Samuel Défago in his article describes a neat way to create block IMP implementation calling super, his original article can be found here

    The relevant code is:

    #import 
    #import 
    
        const char *types = method_getTypeEncoding(class_getInstanceMethod(clazz, selector));
        class_addMethod(clazz, selector, imp_implementationWithBlock(^(__unsafe_unretained id self, va_list argp) {
            struct objc_super super = {
                .receiver = self,
                .super_class = class_getSuperclass(clazz)
            };
    
            id (*objc_msgSendSuper_typed)(struct objc_super *, SEL, va_list) = (void *)&objc_msgSendSuper;
            return objc_msgSendSuper_typed(&super, selector, argp);
        }), types);
    

提交回复
热议问题