簡體   English   中英

從數組訪問元素時應用崩潰

[英]App crashes while accessing an element from array

我使用下面的代碼動態地向數組添加元素。

for (response in jsonDic[@"value"][@"options"]){
                 NSMutableArray *notifyText = [[NSMutableArray alloc]init];
                 [notifyText  addObject: jsonDic[@"value"][@"options"][response]];
                 NSLog(@"it is%@",notifyText[1]);
             }

當我嘗試使用notifyText[1]訪問時,我缺少什么邏輯?

您每次都創建notifyText Array,因此每次都創建它,並且僅添加一個值

請喜歡

 NSMutableArray *notifyText = [[NSMutableArray alloc]init];
for (response in jsonDic[@"value"][@"options"]){
                 [notifyText  addObject: jsonDic[@"value"][@"options"][response]];
                 }
 NSLog(@"it is%@",notifyText[1]);

數組中的索引以0開頭。第一個元素的索引為0。 嘗試

 NSLog(@"it is%@",notifyText[0]);

您在for循環內分配了名為“ notifyText”的MutableArray,該循環每次都會分配,對於最后一個值進行初始化,並在0索引處添加對象,然后嘗試從索引1獲取,這就是應用程序崩潰的原因。在for循環上方或ViewDidLoad方法中執行一件事alloc數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM