Replacing Objective-C Foundation function implementations

后端 未结 1 1068
花落未央
花落未央 2021-01-07 08:52

Is there a way to replace the implementation of an Objective-C Foundation function, such as the NSClassFromString function for example? I am of course aware of class_replace

1条回答
  •  抹茶落季
    2021-01-07 09:47

    Those functions are just C functions and/or macros (Objective C is built on C), and you can't replace a C function.

    However, you can use a define to mask the name:

    Class MyNSClassFromString( NSString* blah ) {
        return whatever;
    }
    
    #define NSClassFromString MyNSClassFromString
    

    Now from that point on, calling NSClassFromString(@"hi") will call the custom function. Note this has several limitations: It will not change any code which is above the define (or any code within libraries you're using), it will often make intellisense unhappy, and it won't work if NSClassFromString is defined as a macro in the first place (you can add #undef NSClassFromString before the define in that case).

    Generally, I wouldn't recommend this, but if you really want to do it, the possibility is there.

    0 讨论(0)
提交回复
热议问题