我正在尝试使用以下代码将NSArray复制到NSMutableArray中,但它因未捕获的异常错误而崩溃。
实际响应数组结果:
dataroot = (
1,
2,
3
);
法典:
@interface MobileTestViewController ()
{
NSMutableArray *mainMutArray ;
}
@end
@implementation MobileTestViewController
- (void)viewDidLoad {
[super viewDidLoad];
mainMutArray = [[NSMutableArray alloc]init];
}
NSMutableArray *responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSArray *dataarray = [responseArray valueForKey:@“dataroot”];
mainMutArray = [[NSMutableArray alloc] initWithArray: dataarray];
@end
错误
由于未捕获的异常"NSInvalidArgumentException"而终止应用程序,原因:"-[__NSCFNumber isEqualToString:]:无法识别的选择器发送到实例 0xb000000000000013">
如何正确地将该阵列复制到 NSMutableArray 中。
看来你混淆了NSArray
和NSDictionary
.从 JSON 序列化中获取的对象是数组还是字典?使用调试器或记录这是哪种类:
NSMutableArray *responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
如果它是一个数组,则以下代码崩溃,因为您不使用字符串键索引到数组中,而是使用整数索引。
NSArray *dataarray = [responseArray valueForKey:@“dataroot”];
如果原始对象是字典,请尝试以下代码:
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!responseDictionary) {
// handle error
}
NSArray *dataArray = responseDictionary[@"dataroot"];
请在 NSMutableArray 分配末尾使用 ">muttablecopy" 来解决问题。
为键方法寻找对象。
NSArray *dataarray = [responseArray objectForKey:@“dataroot”];
mainMutArray = [NSMutableArray arrayWithArray: dataarray];
希望它有效...