访问数组中的元素时应用程序崩溃
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]
访问时,我缺少的逻辑是什么?
数组中的索引从 0 开始。第一个元素的索引为 0。尝试
NSLog(@"it is%@",notifyText[0]);
你在 for 循环中分配了名为 "notifyText" 的 MutableArray,每次都在分配它,它被初始化为最后一个值,对象被添加到 0 索引,你正试图从索引 1 获取,即这就是为什么应用程序在 for 循环上方或 ViewDidLoad 方法中获得 crashed.Do alloc 数组的原因。
您每次都创建了 notifyText
数组,因此每次分配并只添加一个值
请点赞
NSMutableArray *notifyText = [[NSMutableArray alloc]init];
for (response in jsonDic[@"value"][@"options"]){
[notifyText addObject: jsonDic[@"value"][@"options"][response]];
}
NSLog(@"it is%@",notifyText[1]);
我正在使用以下代码向数组动态添加元素。
for (response in jsonDic[@"value"][@"options"]){
NSMutableArray *notifyText = [[NSMutableArray alloc]init];
[notifyText addObject: jsonDic[@"value"][@"options"][response]];
NSLog(@"it is%@",notifyText[1]);
}
当我尝试使用 notifyText[1]
访问时,我缺少的逻辑是什么?
数组中的索引从 0 开始。第一个元素的索引为 0。尝试
NSLog(@"it is%@",notifyText[0]);
你在 for 循环中分配了名为 "notifyText" 的 MutableArray,每次都在分配它,它被初始化为最后一个值,对象被添加到 0 索引,你正试图从索引 1 获取,即这就是为什么应用程序在 for 循环上方或 ViewDidLoad 方法中获得 crashed.Do alloc 数组的原因。
您每次都创建了 notifyText
数组,因此每次分配并只添加一个值
请点赞
NSMutableArray *notifyText = [[NSMutableArray alloc]init];
for (response in jsonDic[@"value"][@"options"]){
[notifyText addObject: jsonDic[@"value"][@"options"][response]];
}
NSLog(@"it is%@",notifyText[1]);