从函数中获取局部变量并在另一个可以动态更改的函数中实现该变量
我的应用程序有一个函数,它从 NSTextField
获取一个值,然后声明该变量,如下所示:
- (IBAction)startTimer
//all the other code
int totalTime = secs + hoursInSeconds + minutesInSeconds
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
然后,我想在另一个函数中使用局部变量 totalTime
处理NSTimer
。
- (void)timerHandler
//all other code
totalTime = totalTime - 1;
//invalidate timer when it reaches 0
if (totalTime == 0.0) {
[timer invalidate];
然而,由于变量totalTime是一个局部变量,我无法使用该值,并且我无法移动代码,因为NSTimer每1秒调用一次它,并且用户可能会更改该变量(从而重新声明它)。
那么,有什么方法可以从函数中获取局部变量并在另一个可以动态更改的函数中实现该变量吗?或者我可以仅使用一个函数来实现 NSTimer 倒计时吗
my app has a function, it gets a value from a NSTextField
and then declare the variable, like this:
- (IBAction)startTimer
//all the other code
int totalTime = secs + hoursInSeconds + minutesInSeconds
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
then, i want to use the local variable totalTime
in another function which processes the NSTimer
.
- (void)timerHandler
//all other code
totalTime = totalTime - 1;
//invalidate timer when it reaches 0
if (totalTime == 0.0) {
[timer invalidate];
however, as the variable totalTime is a local variable, i cannot use the value, and i cannot move the code over as NSTimer calls it every 1 sec and as the user may change the variable (and thus redeclaring it).
so, is there any way i can get a local variable from a function and implement the variable in another function which can be changed dynamically? or can i implement a NSTimer countdown by just using one function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将该值包装在计时器的
userInfo
中:或者只是将其设为实例变量。
You could wrap the value in the timer's
userInfo
:Or just make it an instance variable.
好吧,这是一个有趣的变量,它可以使用局部变量,而不是实例变量,但仅适用于 Mac OS 10.6/iOS 4 及更高版本:
警告:
由于我是从手机发送此消息,因此我不能 100% 确定
timerHandler:
中的转换。但这是沿着这条线的事情......您应该能够完全省略演员阵容,但肯定会看到警告。
Well, here's a fun one that works with local variables, instead of instance variables but only on Mac OS 10.6/iOS 4 and above:
Caveat:
Since I'm sending this from my phone, I am not 100% sure about the cast in
timerHandler:
. But it's something along this line...You should be able to omit the cast altogether, but will definitely see a warning then.