【发布时间】:2011-12-01 11:45:55
【问题描述】:
我是 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”,内容不会改变。 是否有可能做到这一点?解决方案?
【问题讨论】:
-
看起来您的代码应该可以工作。您在哪里检查并找到未更改的值?
-
在每次执行扫描方法时,我都会使用断点或日志检查变量值,并且它始终被赋值为“hello”。相反,我想将变量值 my_string 永久更改为新值,以便我可以从同一个 .m 文件中的另一个函数中读取它。
-
我认为显示的代码没有任何问题。是否可以看到整个“扫描”代码?
-
- (void) awakeFromNib { [[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scan:) userInfo:nil repeats:YES] fire]; } - (void) scan:(NSTimer *)timer{ NSString *string_2 = @"value calculated by previous computation"; if(string_2 != my_string){ my_string = string_2; } }
标签: objective-c cocoa xcode4 global-variables nstimer