开发者

Objective C: Call variable from another method

开发者 https://www.devze.com 2023-02-04 17:42 出处:网络
I\'m trying to access an NSTimer in a method called getTimer in another method. - (NSTimer *)getTimer{

I'm trying to access an NSTimer in a method called getTimer in another method.

- (NSTimer *)getTimer{      
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector: @selector(produceBricks) userInfo:nil repeats:YES];
return timer;
[timer release];
}

I'm trying to stop the timer in another method (a method that would pause the game) by using:

if ([getTimer.timer isValid]) {
    [getTimer.timer invalidate];
}

I'm assuming this i开发者_高级运维s not the correct syntax being it tells me getTimer is undeclared. How would I access the timer so I can stop it?


getTimer is a method, not an object, so you can't send messages to it or access properties. Rather, assuming that the method is in the same class as the one calling it, you would call it like this:

NSTimer *timer = [self getTimer];
if ([timer isValid]) [timer invalidate];
//...

Also, you're trying to release your timer in the getTimer method after the return statement. This code will never be executed (the method has already ended) - which is good in this case, because you shouldn't release the timer, it's already autoreleased. I'd recommend that you read something on Objective-C memory management and naming conventions.


Make the timer an instance variable instead of creating in within getTimer. Then it will be accessible anywhere within the class as follows:

in MyClass.h

NSTimer* timer;

I would implement a startTimer and stopTimer method.

- (void) startTimer {
    timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector: @selector(produceBricks) userInfo:nil repeats:YES];
}


- (void) stopTimer {
    if([timer isValid]) {
        [timer invalidate];
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消