首先是新手问题:选择器和方法之间有什么区别?
其次是新手问题(谁会想到):我需要基于实例变量循环一些代码并在循环之间暂停,直到满足某些条件(当然基于实例变量).我看着睡觉,我看着NSThread.在通过这些选项进行的两次讨论中,很多人问我为什么不使用NSTimer,所以我在这里.
好的,这很简单,让方法(选择器?)按计划触发.我遇到的问题是我不知道如何在代码NSTimer触发时看到我在计时器外设置的实例变量.我需要从NSTimer选择器代码中看到这些变量,因为我1)将更新它们的值,2)将根据这些值设置标签.
这里有一些代码显示了这个概念......最终我也基于myVariable使定时器无效,但是为了清晰代码,我已经排除了它.
MyClass *aMyClassInstance = [MyClass new];
[aMyClassInstance setMyVariable:0];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doStuff) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(doSomeOtherStuff) userInfo:nil repeats:YES];
- (void) doStuff {
[aMyClassInstance setMyVariable:11]; // don't actually have access to set aMyClassInstance.myVariable
[self updateSomeUILabel:[NSNumber numberWithInt:aMyClassInstance.myVariable]]; // don't actually have access to aMyClassInstance.myVariable
}
- (void) doSomeOtherStuff {
[aMyClassInstance setMyVariable:22]; // don't actually have access to set aMyClassInstance.myVariable
[self updateSomeUILabel:[NSNumber numberWithInt:aMyClassInstance.myVariable]]; // don't actually have access to aMyClassInstance.myVariable
}
- (void) updateSomeUILabel:(NSNumber *)arg{
int value = [arg intValue];
someUILabel.text = [NSString stringWithFormat:@"myVariable = %d", value]; // Updates the UI with new instance variable values
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该userInfo参数传输任意对象.在这种情况下,您aMyClassInstance以userInfo身份传递:
MyClass *aMyClassInstance = [MyClass new];
[aMyClassInstance setMyVariable:0];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doStuff) userInfo:aMyClassInstance repeats:YES];
Run Code Online (Sandbox Code Playgroud)
在计时器回调(必须带参数)中,你userInfo从计时器中取回并投射它:
- (void) doStuff:(NSTimer *)timer {
MyClass *instance = (MyClass *)[timer userInfo];
[instance setMyVariable:11];
[self updateSomeUILabel:[NSNumber numberWithInt:instance.myVariable]];
}
Run Code Online (Sandbox Code Playgroud)
整洁的是计时器保留userInfo参数.
| 归档时间: |
|
| 查看次数: |
2150 次 |
| 最近记录: |