NSTimer userInfo。对象如何传递给选择器?

时间:2012-03-01 19:45:04

标签: ios nstimer userinfo

我有这段代码:

-(void)startRotation:(RDUtilitiesBarRotation)mode {
    rotationTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(rotateSelectedItem:) userInfo:[NSNumber numberWithInt:mode] repeats:YES];
}
-(void)rotateSelectedItem:(NSNumber*)sender {
    float currAngle = [selectedItem currentRotation];
    if ([sender intValue] == RDUtilitiesBarRotationLeft) {
        [selectedItem rotateImage:currAngle - 1];
    }
    else {
        [selectedItem rotateImage:currAngle + 1];
    }
}
-(void)stopRotation {
    [rotationTimer invalidate];
    rotationTimer = nil;
}

当用户按住按钮时,目标开始旋转视图。当用户释放它时,计时器将停止。

但我是这样说的:

  

- [__ NSCFTimer intValue]:无法识别的选择器发送到实例0x4ae360

但是如果我在userInfo中调用一个NSNumber类,为什么我要收到定时器呢?

感谢。

3 个答案:

答案 0 :(得分:25)

您的计时器操作方法应该如下所示

-(void)rotateSelectedItem:(NSTimer*)sender

您可以通过执行

来获取userInfo
NSNumber *userInfo = sender.userInfo;

答案 1 :(得分:2)

您误解了您在计时器中注册的选择器的签名。发件人是NSTimer*,而不是您传递给其构造函数的userInfo对象:

-(void)rotateSelectedItem:(NSTimer*)sender
{
    float currAngle = [selectedItem currentRotation];
    if ([sender.userInfo intValue] == RDUtilitiesBarRotationLeft)
    {
        [selectedItem rotateImage:currAngle - 1];
    }
    else
    {
        [selectedItem rotateImage:currAngle + 1];
    }
}

答案 2 :(得分:2)

来自文档:

  

计时器触发时发送到目标的消息。选择器必须   有以下签名:

- (void)timerFireMethod:(NSTimer*)theTimer