|
TOP
|
|
Objective-C对象模型及应用(三)
|
oldMethod2 = class_getInstanceMethod([UIImagePickerController class], @selector(preferredInterfaceOrientationForPresentation));
Method newMethod2 = class_getInstanceMethod([ImagePickerReplaceMethodsHolder class], @selector(preferredInterfaceOrientationForPresentation));
method_setImplementation(oldMethod2, method_getImplementation(newMethod2));
}
}
|
通过如上代码,我们就针对iOS特定版本的有问题的系统库函数打了Patch,使问题得到解决。 开源界的使用 有少量不明真相的同学以为苹果在审核时会拒绝App使用以上API,这其实是对苹果的误解。使用如上API是安全的。另外,开源界也对以上方法都适当的使用。例如:
- 著名的网络库AFNetworking。AFNetworking网络库(v1.x版本)使用了class_replaceMethod方法(AFHTTPRequestOperation.m文件第105行)
- Nimbus。Nimbus是著名的工具类库,它在其core模块中提供了
NIRuntimeClassModifications.h文件,用于提供上述API的封装。
- 国内的大众点评iOS客户端。该客户端使用了他们自己开发的基于Wax修改而来的WaxPatch,WaxPatch可以实现通过服务器更新来动态修改客户端的逻辑。而WaxPatch主要是修改了wax中的wax_instance.m文件,在其中加入了class_replaceMethod来替换原始实现,从而实现修改客户端的原有行为。
总结 通过本文,我们了解到了Objective-C语言的对象模型,以及Objective-C语言对象模型中对isa swizzling和method swizzling的支持。本文也通过具体的实例代码和开源项目,让我们对该对象模型提供的动态性有了更加深刻的认识。 后记 文章发表后,一些同行指出在ARM64的CPU下,isa的内部结构有变化。这点我是知道的,不过希望以后再撰文讨论。感兴趣的同学可以查看苹果今年WWDC2013的视频:《Session 404 Advanced in Objective-C》。 参考链接
- https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Introduction/Introduction.html
- http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
- http://www.deva lot.com/articles/2011/11/objc-object-model.html
- http://www.cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html
- http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
- gunstep的实现源码
- http://algorithm.com.au/downloads/talks/objective-c-internals/objective-c-internals.pdf
- http://opensource.apple.com/source/objc4/objc4-532/runtime/
- https://github.com/AFNetworking/AFNetworking
- https://github.com/jverkoey/nimbus
- https://github.com/mmin18/WaxPatch 本文出自:http://blog.devtang.com/, 原文地址:http://blog.devtang.com/blog/2013/10/15/objective-c-object-model/, 感谢原作者分享。
|