Thread 5:EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)

废话不说,直接说错误的原因

这是我的代码

dispatch_async(    dispatch_get_global_queue(0, 0), ^{
        NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:[NSURL URLWithString:@"http://api.breadtrip.com/hunter/products/more/?city_name=北京&lat=40.02935864560207&lng=116.337422268&sign=eb90993b3a68c75dadaacb4a9aa00c3b&start=0"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
              id anyObject = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:location] options:NSJSONReadingAllowFragments error:&error];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"anyObject:%@",anyObject);
                NSLog(@"error:%@",error);
            });
        }];
        [task resume];
    });

我这是使用 NSURLSession 来请求网络,返回 JSON 格式的数据,从写法上来看应该是没有问题的,但是一运行程序就会崩溃.


屏幕快照 2016-01-12 22.45.12.png

这是崩溃日志

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

解决思路:

1.通过打断点的方式来调试程序:


Thread 5:EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)_第1张图片
屏幕快照 2016-01-12 22.52.20.png

这是会发现当走到 53行代码的时候程序直接崩溃,于是查看virables View 变量打印区域

2.发现犯了一个低级错误,将 URL 中带有中文的链接直接在编译器中请求,如图:提示不支持的 URL .
但是这种带有中文的 URL 在浏览器中是能直接打开的,但是 Xcode 不支持.


Thread 5:EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)_第2张图片
屏幕快照 2016-01-12 22.54.27.png

3.解决方法:
将 URL 中含有中文的参数拼接成非中文的类型,这里只介绍一种方法,将中文通过百分号转码的方式,转为系统能够识别的 URL ,格式:%E5%8C%97%E4%BA%AC

NSString *u = @"北京";
    NSString *e = [u stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet controlCharacterSet]];
    NSLog(@"%@",e);

4.在将这个变量拼接到 URL 的参数中对应的位置即可.

你可能感兴趣的:(Thread 5:EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0))