objective-c 编程总结(第六篇)运行时操作 - 方法交换
后面主要介紹oc類的運行時行為。這里面包括運行時方法的更換,消息的轉發,以及動態屬性。這些對于面向方面編程AOP的熱愛者還是很有用的,當然還有很多其他的作用,例如可配置編程之類的。但是按照我之前在java和dotnet的編程經驗,這些都是使用性能為代價的。所以盡量在程序開始部分完成操作,而不是用于程序行為的代碼。
第一段代碼是方法交換。下面的例子將使用自己的代碼替換[NSString stringByAppendingPathComponent]方法的實現。
這里是替換代碼:
NSString * NSStringstringByAppendingPathComponent(id SELF, SEL _cmd, NSString * path){//開發文檔推薦的是這種定義形式,其實在方法交換場景下,這是沒有必要的,你甚至可以給一個().但是如果你要替換的方法實際并不存在,那么這個定義形式是必須的。NSLog(@”this is a fake imp for method %@”, NSStringFromSelctor(_cmd));NSLog(@”I won’t do anything! but I will return a virus!”);//瘋狂醫生的邏輯return [NSString stringWithCString: “virus!!!” encoding:NSUTF8StringEncoding];}下面是方法交換的代碼:
Class strcls = [NSString class];
SEL oriStringByAppendingPathComponent = @selector(stringByAppendingPathComponent:);
class_replaceMethod(strcls,
oriStringByAppendingPathComponent,
(IMP)NSStringstringByAppendingPathComponent,
NULL);
//后面的type參數可以是NULL。如果要替換的方法不存在,那么class_addMethod會被調用,type參數將被用來設置被添加的方法
/*
Apple development reference 的描述如下:
type參數:An array of characters that describe the types of the arguments to the method. For possible values, see Objective-C Runtime Programming Guide > Type Encodings. Since the function must take at least two arguments—self and _cmd, the second and third characters must be “@:” (the first character is the return type).
-
If the method identified by name does not yet exist, it is added as if class_addMethod were called. The type encoding specified by types is used as given.
-
If the method identified by name does exist, its IMP is replaced as if method_setImplementation were called. The type encoding specified by types is ignored.
*/
posted on 2012-03-13 16:20 一十一王 閱讀(...) 評論(...) 編輯 收藏轉載于:https://www.cnblogs.com/walaqi/archive/2012/03/13/2394038.html
總結
以上是生活随笔為你收集整理的objective-c 编程总结(第六篇)运行时操作 - 方法交换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 长期股权投资和私募股权投资的区别
- 下一篇: 头回遇见网上找不到的问题,“缺少实例ID