obj-c編程06:反射與元編程初步
我們知道對於現如今的動態語言比如ruby而言,反射和元編程以及支持的非常靈活了,你完全可以跳過常規的手段,而利用反射來查詢或調用對象的私有方法。而obj-c對反射的支持略顯小繁瑣,而且在開了ARC後同樣出錯。就算不開ARC,為啥明明有那個方法卻不能調用呢?為啥double變量不讓直接轉成id呢?蛋疼啊,上代碼:
#import <Foundation/Foundation.h> @interface A:NSObject{ double i; } @property double i; -(double)mul:(double)x; -(void)show; @end @implementation A @synthesize i; -(double)mul:(double)x{ return i * x; } -(void)show{ NSLog(@"[A obj]i : %f",i); } @end @interface B:NSObject{ int i; } @property int i; -(int)mul:(int)x; -(void)show; @end @implementation B @synthesize i; -(int)mul:(int)x{ return i * x; } -(void)show{ NSLog(@"[B obj]i : %d",i); } @end int main(int argc,char *argv[]) { @autoreleasepool{ NSLog(@"hello obj-c!"); id obj = [[A alloc] init]; if([obj respondsToSelector: @selector(setI:)]) [obj performSelector: @selector(setI:) withObject:(id)(int)99.99]; [obj show]; //why show can exec??? SEL action_mul = @selector(mul); SEL action_i = @selector(i); if([obj respondsToSelector: action_mul] && [obj respondsToSelector: action_i]) NSLog(@"%f * %f is %f",[obj respondsToSelector :action_i],99.99,[obj respondsToSelector: action_mul]); } return 0; }
不能開ARC,編譯運行如下:
apple@kissAir: objc_src$clang -framework Foundation 2.m -o 2
2.m:58:27: warning: format specifies type 'double' but the argument has type
'BOOL' (aka 'signed char') [-Wformat]
...NSLog(@"%f * %f is %f",[obj respondsToSelector :action_i],99.99,[obj resp...
~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%hhd
2.m:58:68: warning: format specifies type 'double' but the argument has type
'BOOL' (aka 'signed char') [-Wformat]
...%f",[obj respondsToSelector :action_i],99.99,[obj respondsToSelector: action_mul]);
~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%hhd
2 warnings generated.
apple@kissAir: objc_src$./2
2014-06-30 09:27:33.968 2[1010:507] hello obj-c!
2014-06-30 09:27:33.970 2[1010:507] [A obj]i : 0.000000
很明顯沒有執行方法!為啥呢,不知道啊!
最後更新:2017-04-03 06:03:10