【发布时间】:2011-06-24 03:10:09
【问题描述】:
由于某些原因,我必须保留原始代码而不进行修改,但尝试将系统 API 重定向到我的代码中,然后回调到原始代码。例如,我想在[NSString stringWithFormat:] 中做更多的事情。
现在我尝试使用方法调配。但似乎NSString在main运行时没有加载,我将swizzling方法移动到MyAppDelegate。之后class_getInstanceMethod([NSString class], @selector(stringWithFormat:)) 不是零。但是,swizzling 方法仍然不起作用,因为class_getInstanceMethod([NSString class], @selector(override_stringWithFormat:)) 仍然为零,我应该如何解决这个问题?
谢谢, 俱乐部
@interface NSString (MyNSString)
+ (id)stringWithFormat:(NSString *)format, ...;
@end
@implementation NSString (MyNSString)
+ (id)stringWithFormat:(NSString *)format, ... {
//do something...
[NSString stringWithFormat:format];
}
@end
这是 MyAppDelegate 中的代码
#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:)];
}
【问题讨论】:
标签: iphone objective-c ios xcode cocoa