Override setter method and get “Local declaration of xxx hides instance variable”

浪尽此生 提交于 2019-12-24 06:47:08

问题


I have a integer variable, for example, timeSignature, declared it in .h file, and synthesized a pair of setter/getter methods:

in .h:

@interface Metronome : NSObject {
    int timeSignature;
}
@property (nonatomic) int timeSignature;

in .m:

@synthesize timeSignature;

I wish to override the setter method: when user set a new value to it, it does something else as well as changing to new value:

- (void) setTimeSignature:(int)timeSignature {
    self.timeSignature = timeSignature; //hides instance variable warning at this line
    [self doesSomethingElse];
}

And heres the problem, the local variable and the instance variable have the same name.

How can I avoid this?


回答1:


Name your ivar _timeSignature and make @synthesize timeSignature = _timeSignature;




回答2:


Rename the argument variable name:

- (void) setTimeSignature:(int)newTimeSignature { 
    timeSignature = newTimeSignature; //hides instance variable warning at this line 
    [self doesSomethingElse]; 
} 

Also, don't use the property from within the setter, this will create an infinite loop! self.timeSignature = will call setTimeSignature!

This is one of the reasons people use underscore names (_timeSignature) as the backing ivar for properties.




回答3:


Simply renaming method parameter should fix the issue. Also your code produces infinite recursion as you actually call your setter method again - you need to remove property call as well:

- (void) setTimeSignature:(int)timeSignature_ {
    timeSignature = timeSignature_; //hides instance variable warning at this line
    [self doesSomethingElse];
}



回答4:


Rename the parameter. I use aTimeSignature or newTimeSignature.

Also, and this is a bigger problem:

self.timeSignature = someVar;

is merely syntactic sugar for

[self setTimeSignature: somevar];

The dot notation is misleading you into thinking the property is different from the setter. This is not true, the property is the setter and getter. What you really have is this:

- (void) setTimeSignature:(int)timeSignature {
    [self setTimeSignature: timeSignature]; //hides instance variable warning at this line
    [self doesSomethingElse];
}

You should be able to see the obvious difficulty once you change the notation.

If you are new to Objective-C, you should really avoid dot notation until you are thoroughly confident you understand exactly what it does (this is the advice of the Big Nerd Ranch guide to iOS programming).



来源:https://stackoverflow.com/questions/10311169/override-setter-method-and-get-local-declaration-of-xxx-hides-instance-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!