Objective-C“,如果”声明不保留 [英] Objective-C "if" statements not retaining

查看:148
本文介绍了Objective-C“,如果”声明不保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题的标题有点混乱,但在这里它无论如何:

I know the title of this question is a bit confusing, but here it goes anyway:

我创建一个NSString后如果语句,但它似乎不希望保留语句外。我的条件如下:

I'm creating an NSString after an if statement but it just doesn't seem to want to retain outside of the statement. My conditional looks like this:

if ([[password stringValue] isEqualToString:@""]) {
    NSString *pwd = [[NSString alloc]initWithString:@"password"];
}
else {
    NSString *pwd = [[NSString alloc]initWithFormat:@"%@", [password stringValue]];
}

...我调用 pwd 稍后在脚本中这样:

... and I call pwd later in the script like this:

NSArray *arguments;
arguments = [NSArray arrayWithObjects: ip, pwd, nil];
[task setArguments: arguments];

但是当我这样做时,第一个代码片断会返回未使用的变量'pwd',后一个调用的结果是'pwd'undeclared 的错误。

But when I do so in this way, the first snippet returns a warning of Unused variable 'pwd' and the latter call ends up in an error of 'pwd' undeclared.

我在这里做错了什么?提前致谢。 ;)

What am I doing wrong here? Thanks in advance. ;)

推荐答案

使用:


NSString* pwd = nil;
if ([[password stringValue] isEqualToString:@""]) {
    pwd = [[NSString alloc]initWithString:@"password"];
} else {
    pwd = [[NSString alloc]initWithFormat:@"%@", [password stringValue]];
}

问题是每个块引入一个范围。变量仅在定义的范围内存在(从声明点到声明的范围结束存在一个变量)。虽然pwd指向的内存将比if ... else块延长,但是名为pwd的指针将在声明的if ... else块之后停止存在。在块之前声明指针将pwd向上移动一个作用域。

The problem is that each block introduces a scope. A variable exists only in the scope in which it is defined (a variable exists from the point of declaration to the end of the scope it is declared). Although the memory pointed to by "pwd" will outlast the if...else block, the pointer named pwd will cease to exist after the if...else block in which it is declared. Declaring the pointer before the block moves pwd up one scope.

这篇关于Objective-C“,如果”声明不保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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