Scope of variables Objective C

2019-02-18 09:05发布

Do variables declared in methods get erased after the method call is done? Ie If i have the method "someMethod" and every time it is called i want to return a different NSString from a stack property will the method return the next object on the stack or will it keep returned the first index since x is erased at the end of the method call. I know if C that variables are erased after function calls, is it the same in objective c? Would using a seperate property for the variable x some this problem? Thanks

(Double) someMethod{
int x;
[self.stack objectAtIndex:x];
x++;
}

After reading the comments I tried creating a property to replace x and here is what I wrote but I get an error warning stating "local declaration of "_location" hides instance variable" What does this mean?

@property (nonatomic) int location;
@synthesize location=_location;

-(int) location{
    if(!_location){
        int _location = 0;
     //warning is here 
    return _location;
     }
_location++;
return _location;

}

 (Double) someMethod{
int x;
[self.stack objectAtIndex:self.location];
x++;
}

3条回答
我只想做你的唯一
2楼-- · 2019-02-18 09:23

Yes, the lifetime of local variables is limited to the time the enclosing function is executing (with exceptions for blocks, but you're not using those in this case).

Your counter x is probably best as an object property, if you want to maintain its value between calls to someMethod.

查看更多
做个烂人
3楼-- · 2019-02-18 09:33

Do variables declared in methods get erased after the method call is done?

Yes

Objective C methods are implemented "on top" of C functions, so the same rules apply. In particular, your code exhibits undefined behavior (reading of uninitialized variable).

To fix this issue, add an instance variable x in place of the automatic variable that your code snippet currently declares.


automatic is the "official" name of "stack" variables, i.e. variables that you declare inside your methods / functions.

查看更多
狗以群分
4楼-- · 2019-02-18 09:36

Answering to your question about the warning...

It is just saying that when you declare inside your if in method location()

int _location = 0;

this local variable has the same name as the property you created earlier

@syntenshize location = _location

Thus it gets confusing (for the programmer) to know which one he is using at the moment.

The compiler will understand that inside the if _location is an int ... and outside the if _location is your property.

查看更多
登录 后发表回答