关于Objective-C中Method Swizzling完美方案的一些疑问

Pete_Ruan 2017-04-09 05:21:00
先贴代码
typedef IMP *IMPPointer;

BOOL class_swizzleMethodAndStore(Class class, SEL original, IMP replacement, IMPPointer store) {
IMP imp = NULL;
Method method = class_getInstanceMethod(class, original);
if (method) {
const char *type = method_getTypeEncoding(method);
imp = class_replaceMethod(class, original, replacement, type);
if (!imp) {
imp = method_getImplementation(method);
}
}
if (imp && store) { *store = imp; }
return (imp != NULL);
}

@implementation NSObject (FRRuntimeAdditions)
+ (BOOL)swizzle:(SEL)original with:(IMP)replacement store:(IMPPointer)store {
return class_swizzleMethodAndStore(self, original, replacement, store);
}
@end


最近在学习 OC 的 runtime,在 Stack Overflow 上看到了一套完美的 Method Swizzling 代码,其中有几个点不是很懂:
1. class_swizzleMethodAndStore() 函数的最后一个参数 store 是干啥用的
2.这段代码的作者解释,这么写可以替代在 +load 方法中进行 Method Swizzling,因为它是线程安全的,为什么这么写就线程安全了(也可能是我理解错了,请指正)

附上链接:http://stackoverflow.com/questions/5339276/what-are-the-dangers-of-method-swizzling-in-objective-c
求指点,谢谢!
...全文
509 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzia21117 2018-09-14
  • 打赏
  • 举报
回复
从那个链接里可以看到:
@implementation NSView (MyViewAdditions)

static void MySetFrame(id self, SEL _cmd, NSRect frame);
static void (*SetFrameIMP)(id self, SEL _cmd, NSRect frame);

static void MySetFrame(id self, SEL _cmd, NSRect frame) {
// do custom work
SetFrameIMP(self, _cmd, frame);
}

+ (void)load {
[self swizzle:@selector(setFrame:) with:(IMP)MySetFrame store:(IMP *)&SetFrameIMP];
}

store传入的是SetFrameIMP这个变量的地址,然后通过*store = imp;就可以把imp赋值给SetFrameIMP,之后就可以通过SetFrameIMP(self, _cmd, frame);来调用之前selector映射的方法了。

29,027

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧