OC 运行时

来源:互联网 发布:知乎 人生目标 编辑:程序博客网 时间:2024/05/04 01:51
  1. #import <objc/objc-class.h>  
  2.   
  3. // create a class with no methods  
  4. @interface EmptyClass : NSObject { }  
  5. @end  
  6.   
  7. @implementation EmptyClass  
  8. @end  
  9.   
  10. // define the function to add as a method  
  11. id sayHello ( id selfSEL _cmd,... )  
  12. {  
  13.   NSLog (@"Hello");  
  14. }  
  15.   
  16. void addMethod ()  
  17. {  
  18.   struct objc_method myMethod; <span style="white-space:pre">             </span>//0 创建method实例  
  19.   myMethod.method_name = sel_registerName("sayHello"); <span style="white-space:pre">     </span>//1.0 为函数名赋值  
  20.   myMethod.method_imp  = sayHello; <span style="white-space:pre">             </span>//1.1 为函数实现赋值  
  21.   
  22.   struct objc_method_list * myMethodList;  
  23.   myMethodList = malloc (sizeof(struct objc_method_list));  
  24.   myMethodList->method_count = 1;  
  25.   myMethodList->method_list[0] = myMethod;<span style="white-space:pre">       </span>//2 将自定义的函数实例添加到 list中  
  26.     
  27.   class_addMethods ( [EmptyClass class], myMethodList );//3 将list绑定到类上面  
  28.     
  29.   // 调用  
  30.   EmptyClass * instance = [[EmptyClass alloc] init];  
  31.   [instance sayHello];  
  32.   [instance release];  
  33. }  
这基本就是OC动态加载的过程。
0 0
原创粉丝点击