从 NSTimer 更改变量值
我是 Cocoa/Objective C 的新手。我必须在 NSTimer
执行的每次迭代中更改全局 NSSTring
变量的值。我已在文件顶部的 appdelegate.m 内声明了该变量,因此它是全局的:
NSString *my_string = @"hello";
我调用 NSTimer
:
[[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scan:) userInfo:nil repeats:YES] fire];
并在扫描内部将新值设置为 my_string
:
- (void) scan:(NSTimer *)timer{
//some execution
my_string = @"the new value";
}
但变量值始终是相同的“hello”,内容不会改变。 可以这样做吗?解决方案?
I'm newbie to Cocoa/Objective C. I've to change a value of a global NSSTring
variable on every iteration of an NSTimer
execution. I've declared the variable inside the appdelegate.m at the top of the file so it's global:
NSString *my_string = @"hello";
I call the NSTimer
:
[[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scan:) userInfo:nil repeats:YES] fire];
and inside scan i set the new value to my_string
:
- (void) scan:(NSTimer *)timer{
//some execution
my_string = @"the new value";
}
but the variable value is always the same "hello", the content won't change.
Is it possible to do this? Solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要调用 fire 方法,预定的计时器将在指定的时间间隔后自动触发。
另外,在 scan: 方法处设置断点以查明它是否被调用。
You do not need to call fire method, the scheduled timer will fire automatically after the specified interval.
Also, set a breakpoint at the scan: method to find out if it is called.
如果您在 .m 文件中声明 my_string 变量,则其他文件将无法看到它(您 #import .h 文件而不是 .m)。你在同一个文件(appdelegate.m)中做定时器的事情吗?
我建议不要使用这样的全局变量,因为随着项目的建立,它常常会造成混乱。您可以将其作为带有访问器的 ivar,也可以将其作为带有静态访问器的 @implementation 块中的静态,以便您可以从任何地方访问唯一的实例。
您可以记录更改以确保其发生或设置断点。
If you declare your my_string variable in the .m file then other files won't be able to see it (you #import the .h files not the .m). Do you do the timer stuff in the same file (appdelegate.m)?
I recommend not having global variables like this as it will often confuse things as the project builds up. You can have it either as an ivar with an accessor, or as static in the @implementation block with a static accessor so that you can have access to a unique instance from anywhere.
You can log the change to make sure it happens or set a breakpoint.