如何在'scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:'中将多个参数传递给选择器

时间:2012-03-01 11:46:20

标签: objective-c parameters userinfo

我知道用户信息用于传递参数,但是如何传递多个参数?

我猜我必须使用一个对象,但由于我对于Objective-c相当新,我不知道这是否正确以及如何去做?

谢谢!

1 个答案:

答案 0 :(得分:4)

创建一个包装器对象,NSArrayNSDictionary,其中包含您需要传递的多个对象,并在userInfo中传递该包装器对象。在接收器上从包装器对象中检索对象。

使用NSDictionary作为包装器的示例代码:

致电代码:

NSString *obj1 = @"string1"; 
NSString *obj2 = @"string2"; 
NSDictionary *wrapper = [NSDictionary dictionaryWithObjectsAndKeys:obj1, @"Object1", obj2, @"Object2", nil];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:wrapper repeats:NO];

接收定时器代码:

- (void)timerFireMethod:(NSTimer*)theTimer {
    NSDictionary *wrapper = (NSDictionary *)[theTimer userInfo];
    NSString * obj1 = [wrapper objectForKey:@"Object1"];
    NSString * obj2 = [wrapper objectForKey:@"Object2"];
    // ...
}
相关问题