繁体   English   中英

无法获取NSString ivar以接受数组中的值

[英]Can't get an NSString ivar to accept a value from an array

我将一些数据(一些浮点数,一些字符串)存储到plist中,然后将其读回。 当我读回它们时,我将它们分配给视图控制器中的某些ivars。 它们只是ivars,不是属性。

浮点数可以很好地使用它们的值,我可以对它们进行NSLog并查看它们是正确的。 但是,无论我尝试什么,我都无法让我的NSString ivars接受字符串值。

示例:数组位置6和7中存储着字符串Portland, OR""Pacific Daylight Time" -从plist读回*array.

这个:

cityName = [NSString stringWithFormat:@"", [array objectAtIndex:6]];
timeZoneName = [NSString stringWithFormat:@"", [array objectAtIndex:7]];
NSLog(@" >cityName from array = %@, and now the iVar is = %@", [array objectAtIndex:6], cityName);
NSLog(@" >timeZoneName from array = %@, and now the iVar is = %@", [array objectAtIndex:7], timeZoneName);

结果:

>cityName from array = Portland, OR, and now the iVar is = 
>timeZoneName from array = Pacific Daylight Time, and now the iVar is = 

我在发生这种情况的方法的末尾放置了一个断点,对于两个NSString ivars,弹出的小消息都说“ Invalid Summary.

cityName = [NSString stringWithFormat:@"%@", [array objectAtIndex:6]];

错误是您错过了格式说明符。 不过,特别是,如果数组中的对象已经是字符串,则可以直接将它们直接分配给ivar:

cityName = [array objectAtIndex:6];

但是要注意对象所有权。 你不能拥有被返回的对象objectAtIndex:所以如果你需要在许多不同的方法来使用这个实例变量,通过发送取得所有权retain ,并采用放弃所有权release 或者,如果您选择将cityName建立为类的保留或复制属性,请使用点符号或访问器方法:

self.cityName = [array objectAtIndex:6];

// or

[self setCityName:[array objectAtIndex:6]];

如果数组包含NSString实例,则无需调用+stringWithFormat: 这浪费了CPU周期,并且取消了与不可变字符串相关的任何潜在优化。 此外,依靠的结果description是永远正确的答案(虽然它是不可避免的亲近与NSString的-这是一个地方,你可以依赖的结果)。

此(固定):

cityName = [NSString stringWithFormat:@"%@", [array objectAtIndex:6]];
timeZoneName = [NSString stringWithFormat:@"%@", [array objectAtIndex:7]];

可能:

cityName = [array objectAtIndex:6];
timeZoneName = [array objectAtIndex:7];

如果需要,请复制它。 正如@dreamlax所说,确保您遵循内存管理规则。

在下面使用

cityName = [NSString stringWithFormat:@"%@", [array objectAtIndex:6]];

您需要将%d或%i用于整数,并将%@用于字符串对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM