日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

objective-c 编程总结(第六篇)运行时操作 - 方法交换

發布時間:2024/1/17 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 objective-c 编程总结(第六篇)运行时操作 - 方法交换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 编程总结(第六篇)运行时操作 - 方法交换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。