|
|
[FractionPost postAsClass:[Fraction class]];
postAsClass,32位系统中,据说还可以用;但是64位系统或者10.6.5更高的版本都不能使用了。它的作用就是使用FractionPost中的方法替代Fraction中的方法!比如,Fraction中的print方法:
-(void) print { printf("%i/%i", numerator, denominator);}
而在FractionPost中,
-(void) print{ printf("posting:%i/%i", numerator, denominator);}
这样对于Fraction对象的实例就会调用FractionPost中的方法了。当然,前提条件是FractionPost是Fraction的子类。@interface FractionPost : Fraction {}
下面要说的是,既然postAsClass不能使用了,我们用什么方法来继续使用这种功能呢?method_exchangeImplementations(originalMethod, replaceMethod);这个运行时函数会帮助我们解决这个函数。要使用这个函数,首先导入头文件#import <objc/runtime.h>完整的用法是:
Method originalMethod = class_getInstanceMethod([Fraction class], @selector(print));Method replaceMethod = class_getInstanceMethod([FractionPost class], @selector(print));method_exchangeImplementations(originalMethod, replaceMethod);
首先获取你要替代的方法,这样做本人认为安全性也提高了,假如使用postAsClass,这样所有子类重写了的方法都会被替代。当然,安全性的提高,代价就是功能的削弱。我相信有一定基础的人都能看懂吧,本人也还在学习基础中。更多相关Method的方法请参考官方library。
http://developer.apple.com/library/mac/#samplecode/MethodReplacement/Introduction/Intro.html |
|