将参数传递给NSTimer中的方法时,应用程序崩溃

时间:2015-02-09 22:33:33

标签: ios objective-c selector nstimer unrecognized-selector

我正在尝试创建一个NSTimer,我可以在其中传递不同的UILabel,它会根据时间改变文本颜色。这是我正在使用的代码示例,希望实现这一目标。我确信它会起作用,但是一旦计时器启动,我的应用程序就会崩溃并显示下面的日志。

为什么会这样?我以为我已经正确设置了所有内容。

·H

IBOutlet UILabel *titleColor;
int time;
NSTimer *timer;

.m

- (void)viewDidLoad {
    [super viewDidLoad];
    timer = [NSTimer scheduledTimerWithTimeInterval:animationDuration target:self selector:@selector(timeCycle:) userInfo:titleColor repeats:YES];
}

- (void)timeCycle:(UILabel *)label {
    time++;
    if (time == 10) {
        time = 0;
    }

    [self labelColorCycle:label];
}

- (void)labelColorCycle:(UILabel *)label {

    if (time == 0) {
        [label setTextColor:[UIColor colorWithRed:100
                                  green:50
                                   blue:75
                               alpha:1]];
    }
    else if (time == 1) {
         // sets another color
    }
}

崩溃报告

2015-02-09 17:17:51.454 Test App[404:30433] -[__NSCFTimer setTextColor:]: unrecognized selector sent to instance 0x14695bb0
2015-02-09 17:17:51.455 Test App[404:30433] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFTimer setTextColor:]: unrecognized selector sent to instance 0x14695bb0'
*** First throw call stack:
(0x228c849f 0x300c2c8b 0x228cd8b9 0x228cb7d7 0x227fd058 0xf70e5 0xf6f17 0x235d9ba1 0x2288ec87 0x2288e803 0x2288ca53 0x227da3c1 0x227da1d3 0x29bd80a9 0x25de87b1 0xf5d41 0x30642aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException

1 个答案:

答案 0 :(得分:3)

timeCycle:的论点是NSTimer而非UILabel。为什么你需要通过标签?这是一个产权?

所以改变你的方法,如:

- (void)viewDidLoad
{
    [super viewDidLoad];
    timer = [NSTimer scheduledTimerWithTimeInterval:animationDuration target:self selector:@selector(timeCycle:) userInfo:nil repeats:YES];
}

- (void)timeCycle:(NSTimer *)timer
{
    time++;
    if (time == 10)
    {
        time = 0;
    }

    [self labelColorCycle:self.titleColor];
}

- (void)labelColorCycle:(UILabel *)label
{

    if (time == 0)
    {
        [label setTextColor:[UIColor colorWithRed:100 green:50 blue:75 alpha:1]];
    }
    else if (time == 1)
    {
         // sets another color
    }
}

如果您需要将标签作为参数传递,请使用NSTimer的{​​{3}}属性。

在这种情况下,您的代码将如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    timer = [NSTimer scheduledTimerWithTimeInterval:animationDuration target:self selector:@selector(timeCycle:) userInfo:self.titleColor repeats:YES];
}

- (void)timeCycle:(NSTimer *)timer
{
    time++;
    if (time == 10)
    {
        time = 0;
    }

    [self labelColorCycle:(UILabel *)[timer userInfo]];
}

- (void)labelColorCycle:(UILabel *)label
{

    if (time == 0)
    {
        [label setTextColor:[UIColor colorWithRed:100 green:50 blue:75 alpha:1]];
    }
    else if (time == 1)
    {
         // sets another color
    }
}