objective-C中的Class(类类型),Selector(选择器SEL),函数指针(IMP)

时间:2023-01-15 18:38:14
今天在园子里看到了一篇牛文“Objective-C 2.0 with Cocoa Foundation--- 5,Class类型,选择器Selector以及函数指针 ”,讲得十分精彩,忍不住把它的代码加上注释整理于此,以便日后查看。个人体会:obj-C中的“Class类型变量”比c#中的Object基类还要灵活,可以用它生成任何类型的实例(但是它又不是NSObject)。而选择器SEL与函数指针IMP,如果非要跟c#扯上关系的话,这二个结合起来,就点类似c#中的反射+委托,可以根据一个方法名称字符串,直接调用方法。"牛"的基类 Cattle.h
#import <Foundation/Foundation.h>

@interface Cattle : NSObject {
int legsCount;
}
- (void)saySomething;
- (void)setLegsCount:(int) count;
@end
 Cattle.m
#import "Cattle.h"

@implementation Cattle

-(void) saySomething
{
NSLog(@"Hello, I am a cattle, I have %d legs.", legsCount);
}

-(void) setLegsCount:(int) count
{
legsCount = count;
}
@end
子类“公牛" Bull.h
#import <Foundation/Foundation.h>
#import "Cattle.h"

@interface Bull : Cattle {
NSString *skinColor;
}
- (void)saySomething;
- (NSString*) getSkinColor;
- (void) setSkinColor:(NSString *) color;
@end
Bull.m
#import "Bull.h"


@implementation Bull

-(void) saySomething
{
NSLog(@"Hello, I am a %@ bull, I have %d legs.", [self getSkinColor],legsCount);
}

-(NSString*) getSkinColor
{
return skinColor;
}

- (void) setSkinColor:(NSString *) color
{
skinColor = color;
}
@end
代理类DoProxy.h (关键的代码都在这里)
#import <Foundation/Foundation.h>

//定义几个字符串常量
#defineSET_SKIN_COLOR @"setSkinColor:"
#defineBULL_CLASS @"Bull"
#defineCATTLE_CLASS @"Cattle"


@interface DoProxy : NSObject {
BOOL notFirstRun;

id cattle[3];
//定义二个选择器
SEL say;
SEL skin;

//定义一个函数指针(传统C语言的处理方式)
void(*setSkinColor_Func)(id,SEL,NSString*);

//定义一个IMP方式的函数指针(obj-C中推荐的方式)
IMP say_Func;

//定义一个类
Class bullClass;
}

-(void) doWithCattleId:(id) aCattle colorParam:(NSString*) color;
-(void) setAllIVars;
-(void) SELFuncs;
-(void) functionPointers;

@end
DoProxy.m
#import "DoProxy.h"
#import "Cattle.h"
#import "Bull.h"

@implementation DoProxy


//初始化所有变量
- (void) setAllIVars
{
cattle[0] = [Cattle new];

bullClass = NSClassFromString(BULL_CLASS);
//即cattle[1],cattle[2]都是Bull类的实例
cattle[1] = [bullClass new];
cattle[2] = [bullClass new];

say = @selector(saySomething);
skin = NSSelectorFromString(SET_SKIN_COLOR);
}


//初始化id
- (void) doWithCattleId:(id) aCattle colorParam:(NSString*) color
{
//第一次运行的时候
if(notFirstRun == NO)
{
NSString *myName = NSStringFromSelector(_cmd);//取得当前正在执行的方法的名字
NSLog(@"Running in the method of %@", myName);
notFirstRun = YES;//修改初次运行标志位
}

NSString *cattleParamClassName = [aCattle className];//取得aCattle的"类名称"

//如果aCattle是Bull或Cattle类的实例
if([cattleParamClassName isEqualToString:BULL_CLASS] || [cattleParamClassName isEqualToString:CATTLE_CLASS])
{
[aCattle setLegsCount:4];//设置牛的4条腿
if([aCattle respondsToSelector:skin])//如果aCattle对应的是类中,有定义方法"setSkinColor"
{
[aCattle performSelector:skin withObject:color];//则调用setSkinColor方法
}
else
{
NSLog(@"Hi, I am a %@, have not setSkinColor!", cattleParamClassName);//否则输出相应的提示信息
}
[aCattle performSelector:say];//最后执行saySomething方法(这二个方法在Bull与Cattle类中都有,所以肯定能运行)
}
else //如果aCattle即不是Bull类也不是Cattle类的实例
{
NSString *yourClassName = [aCattle className];
NSLog(@"Hi, you are a %@, but I like cattle or bull!", yourClassName);//显示这个"异类"的相关信息
}
}

//初始化选择器以及相应函数
- (void) SELFuncs
{
[self doWithCattleId:cattle[0] colorParam:@"brown"];
[self doWithCattleId:cattle[1] colorParam:@"red"];
[self doWithCattleId:cattle[2] colorParam:@"black"];
[self doWithCattleId:self colorParam:@"haha"];//这里故意传入一个异类self(即DoProxy本身),DoProxy当然不是Bull或Cattle
}

//函数指针测试
- (void) functionPointers
{
//取得函数指针的第一种方式
setSkinColor_Func=(void (*)(id, SEL, NSString*)) [cattle[1] methodForSelector:skin];
//上面的语句其实等效于下面这种方法
//IMP setSkinColor_Func = [cattle[1] methodForSelector:skin];

//用第二种方法取得saySomething的函数指针
say_Func = [cattle[1] methodForSelector:say];

//用函数指针的形式调用setSkinColor
setSkinColor_Func(cattle[1],skin,@"verbose");

NSLog(@"Running as a function pointer will be more efficiency!");

//调用saySomething方法
say_Func(cattle[1],say);
}

@end
测试主函数main()
#import <Foundation/Foundation.h>
#import "DoProxy.h"

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
DoProxy *doProxy = [DoProxy new];

[doProxy setAllIVars];
[doProxy SELFuncs];
[doProxy functionPointers];

[doProxy release];
[pool drain];
return 0;
}

运行结果:

2011-02-28 21:40:33.240 HelloSelector[630:a0f] Running in the method of doWithCattleId:colorParam:
2011-02-28 21:40:33.245 HelloSelector[630:a0f] Hi, I am a Cattle, have not setSkinColor!
2011-02-28 21:40:33.247 HelloSelector[630:a0f] Hello, I am a cattle, I have 4 legs.
2011-02-28 21:40:33.248 HelloSelector[630:a0f] Hello, I am a red bull, I have 4 legs.
2011-02-28 21:40:33.250 HelloSelector[630:a0f] Hello, I am a black bull, I have 4 legs.
2011-02-28 21:40:33.251 HelloSelector[630:a0f] Hi, you are a DoProxy, but I like cattle or bull!
2011-02-28 21:40:33.252 HelloSelector[630:a0f] Running as a function pointer will be more efficiency!
2011-02-28 21:40:33.254 HelloSelector[630:a0f] Hello, I am a verbose bull, I have 4 legs.