簡體   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