performSelector & @selector

来源:互联网 发布:淘宝店铺地址是无效的 编辑:程序博客网 时间:2024/05/21 04:16

转载地址:http://blog.sina.com.cn/s/blog_7ff0f30f0100uvl9.html

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 :秒数];

 

如何在 performSelector: withObject:afterDelay 的Object里传入多个参数

转载地址:http://blog.sina.com.cn/s/blog_67a5e472010152v1.html

写代码的时候可能会遇到如下的问题
一个方法

-(void)fooFirstInput:(NSString*)firstsecondInput:(NSString*)second
{

}

有两个或者多个参数
当需要执行performSelector方法并且afterDelay的时候,withObject只能传入一个参数,并且也没有对应的withObjects方法,
这么写是不对的。会报错
 [self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second" afterDelay:15.0]; 


遇到这种情况利用如下的一个小方法可以满足调用多个参数的select method
1.
 - (void) callFooWithArray: (NSArray *) inputArray{    [self fooFirstInput: [inputArray objectAtIndex:0] secondInput: [inputArray objectAtIndex:1]];}  - (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second{ } 

2.
 [self performSelector:@selector(callFooWithArray) withObject:[NSArray arrayWithObjects:@"first", @"second", nil] afterDelay:15.0]; 

 

 

 

原创粉丝点击