变量范围目标 C [英] Scope of variables Objective C

查看:62
本文介绍了变量范围目标 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在方法调用完成后,方法中声明的变量会被删除吗?即如果我有方法someMethod"并且每次调用它时我想从堆栈属性返回一个不同的 NSString 该方法将返回堆栈上的下一个对象还是它会保持返回第一个索引,因为 x 在方法调用结束.我知道 C 是否在函数调用后删除了变量,在目标 c 中是否相同?对变量 x 使用单独的属性是否会出现这个问题?谢谢

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++;
}

阅读评论后,我尝试创建一个属性来替换 x,这是我写的内容,但我收到一条错误警告,指出_location"的本地声明隐藏了实例变量"这是什么意思?

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++;
}

推荐答案

在方法调用完成后,方法中声明的变量会被删除吗?

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

是的

Objective C 方法是在 C 函数的顶部"实现的,因此适用相同的规则.特别是,您的代码表现出未定义的行为(读取未初始化的变量).

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).

要解决此问题,请添加一个实例变量 x 代替您的代码段当前声明的 automatic 变量.


automatic 是堆栈"变量的官方"名称,即您在方法/函数中声明的变量.

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.

这篇关于变量范围目标 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆