obj-c编程06:反射与元编程初步

时间:2020-12-25 00:32:46

我们知道对于现如今的动态语言比如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


很明显没有执行方法!为啥呢,不知道啊!