Object-C中@selector关键字 是用来搜索方法的,将方法转换成SEL类型的变量。
#import <Cocoa/Cocoa.h>
@interface Car : NSObject {
int year;
NSString *make;
NSString *model;}
@property (nonatomic,retain) NSString * model;
@property (nonatomic ,retain )NSString * make;
-(void) setMake :(NSString *)aMake andModel:(NSString *) aModel;@end
上面的代码声明了一个Car类,并且设置其中的两个属性为非原子性的、自动生成getter方法(使用了@property)。
#import "Car.h"
@implementation Car:NSObject
@synthesize make;
@synthesize model;-(void) setMake:(NSString *)aMake andModel:(NSString *)aModel{
make=aMake;
model=aModel;
}@end
上面代码是实现了Car类 ,使用了@synthesize关键字声明 该属性自动生成setter方法。
#import <Foundation/Foundation.h>
#import "Car.h"int main (int argc, const char * argv[]) {
Car * myCar2=[[Car alloc]init];
SEL carMethod=@selector(setMake:andModel:);
[myCar2 performSelector:carMethod withObject:@"11111" withObject:@"2222" afterDelay:10];
NSLog(@"myCar shuxing : %@ ---%@",myCar2.make,myCar2.model);
}
这段代码中@selector 搜索setMake方法 并返回SEL类型的变量。
格式如下:
SEL 变量名 = @selector(方法名 : 第二个参数名 : 参数);
[myCar2 performSelector:carMethod withObject:@"11111" withObject:@"2222" afterDelay:10];
这句话将搜索到的SEL类型的消息 发送给 myCar2对象。 performSelector关键字可以调用到SEL类型的变量。延迟十秒执行。
其语句格式如下:
[消息接受者 performSelector:SEL类型的变量 withObject: 第一个参数 withObject: 第二个参数 afterDelay :秒数];