Change variable value from NSTimer
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 executi开发者_StackOverflow中文版on
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?
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.
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.
- (void) scan:(NSTimer *)timer{
//some execution
my_string = @"the new value";
NSLog(@"Changed my_string to %@", my_string);
}
精彩评论