Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to redirect system API in Objective-C?
    primarykey
    data
    text
    <p>Due to some reasons I have to keep original code without modification, but try to redirect system API into my code and then call back to the original one. For example, I would like to do something more in <code>[NSString stringWithFormat:]</code>. </p> <p>Now I try to use method swizzling. But it seems that <code>NSString</code> is not loaded during the runtime of main, I move swizzling method to <code>MyAppDelegate</code>. After that <code>class_getInstanceMethod([NSString class], @selector(stringWithFormat:)</code>) is not nil. However, the swizzling method is still not working because <code>class_getInstanceMethod([NSString class], @selector(override_stringWithFormat:))</code> is still nil, how should I fix that?</p> <p>Thanks, clu</p> <pre><code>@interface NSString (MyNSString) + (id)stringWithFormat:(NSString *)format, ...; @end @implementation NSString (MyNSString) + (id)stringWithFormat:(NSString *)format, ... { //do something... [NSString stringWithFormat:format]; } @end </code></pre> <p>Here is the code in MyAppDelegate</p> <pre><code>#import "MyNSString.h" -(void) MethodSwizzle:(Class)c replaceOrig:(SEL) origSEL withNew:(SEL) overrideSEL { Method origMethod = class_getInstanceMethod(c, origSEL); Method overrideMethod = class_getInstanceMethod(c, overrideSEL); if(class_addMethod(c, origSEL, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) class_replaceMethod(c, overrideSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); else method_exchangeImplementations(origMethod, overrideMethod); } - (BOOL) application:(UIApplication*) application didFinishLaunchingWithOptions:(NSDictionary *) options { ... //Unit test NSString *a=[NSString override_stringWithFormat:@"Test"]; //returned something Method b = class_getInstanceMethod([NSString class], @selector(override_stringWithFormat:)); //return nil; //do something... [self MethodSwizzle:[NSString class] replaceOrig:@selector(stringWithFormat:) withNew:@selector(override_stringWithFormat:)]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload