开发者

Why does Xcode 4 mark variables as unused even if they are?

开发者 https://www.devze.com 2023-03-27 05:05 出处:网络
I\'m instantiating and scheduling a timer variable but Xcode compiler and analyzer marks my var \"levelScoreTimer\" with 2 warnings like \"warning: unused variable \'levelScoreTimer\' and \"Dead store

I'm instantiating and scheduling a timer variable but Xcode compiler and analyzer marks my var "levelScoreTimer" with 2 warnings like "warning: unused variable 'levelScoreTimer' and "Dead store: Value stored to 'levelScoreTimer' during its initialization is never read". What is wrong with my declaration? The scheduledTimerWithTimeInterval method instantiates and puts the timer on the main run loop. I'm also stopping the timer from selector method inside, so the timer as objects is used for sure. Sometimes in similar cases I break the line into two lines by declaring a type for variabl开发者_JAVA百科e on the first line and making assignment on the second line. But it is not a solution for timer object. Any suggestions? Here is my declaration and assigment:

NSTimer *levelScoreTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTotalScoreLabelFromTimeLeftLabel:) userInfo:nil repeats: YES];


Change the code from

NSTimer *levelScoreTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTotalScoreLabelFromTimeLeftLabel:) userInfo:nil repeats: YES];

to

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTotalScoreLabelFromTimeLeftLabel:) userInfo:nil repeats: YES];


The compiler should be right, are you sure you’re not doing something wrong? Post more code. In each case you can mark the variable as unused:

__unused NSTimer *timer = …;

I use this for example in asserts that get compiled out in the production code and would lead to warnings:

__unused NSString *foo = …;
NSAssert(foo, @"Bar");
// foo no longer used

But in your case I’m almost sure the compiler is right. You say that you “stop the time from the selector method”, you mean from the method that is called when the timer fires? How do you get the pointer to the timer? Because you obviously store it in a local variable that won’t be available there.


You don't show enough of the rest of your code to see if you really use the value stored in levelScoreTimer anywhere. If this is a local variable, take a look in your method if you are assigning something else to it before you use the value you assign it above.

In my experience, the compiler knows such things better than we do. It doesn't miss or forget an assignment, retain or release, like we humans tend to do.


Consider doing this at appropriate place:

[levelScoreTimer invalidate];
levelScoreTimer = nil;

Referring from: How do I use NSTimer?

0

精彩评论

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