繁体   English   中英

iOS-compelationHandler:nil导致应用崩溃

[英]iOS - App Crashes with compelationHandler:nil

嘿,所以我得到了经典的EXC_BAD_ACCESS (Code = 1, address = 0x10) ,似乎无法弄清楚原因。 我通过以下方法得到错误:

+ (void)logoutWithXId:(NSString *)xId compelationHandler:(void (^)(BOOL))hasSucceeded
{
    NSError *error;

    // create json object for a users session
    NSDictionary *session = [NSDictionary dictionaryWithObjectsAndKeys:
                             xId, @"x_id",
                             nil];

    NSData *jsonSession = [NSJSONSerialization dataWithJSONObject:session options:NSJSONWritingPrettyPrinted error:&error];

    NSString *url = [NSString stringWithFormat:@"%@xsession/logout", potCatURL];

    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:30.0];

    NSString *headerValue = [NSString stringWithFormat:@"Token token=%@", APIToken];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:headerValue forHTTPHeaderField:@"Authorization"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonSession length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonSession];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

        if (error == nil)
        {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSInteger statusCode = httpResponse.statusCode;

            if (statusCode == 200)
            {
                //********************* error happens here *******************************
                hasSucceeded(true);
            }
            else
            {
                hasSucceeded(false);
            }
        }
        else
        {
            hasSucceeded(false);
        }
    }];
}

当我这样调用方法时:

[Xsession logoutWithXId:[userInfo stringForKey:@"x_id"] compelationHandler:nil]

我收到EXC_BAD_ACCESS错误,但是当我这样调用时:

[Xsession logoutWithXId:[userInfo stringForKey:@"x_id"] compelationHandler:^(BOOL hasCreated){}]

与一个空的compilerHandler,它运行良好。 为什么会这样,有人可以解释一下吗?

这是由于nil处理程序。 您必须始终执行以下操作:

if (hasSucceeded) {
    hasSucceeded(someValue);
}

崩溃是由于取消引用nil块指针引起的。 这与尝试在nil变量引用上调用方法不同(可以)。 您绝不能取消引用nil块指针。

此处的另一个答案中,有一些很好的信息。

崩溃的原因是您不检查传递的参数是否为nil。 在这种情况下,块是不同的(您应将其视为指向函数的指针,而不是NSObject子类)。 您不能在地址0上调用函数。

要修复它,您应该在调用它之前检查该块是否不为零:

if (hasSucceded) {
    hasSucceeded(value);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM