为什么[[NSError alloc] init]; 在Xcode中抛出错误?

Lud*_*udo 5 nserror alloc ios

我在Xcode中有以下代码:

NSError *error = [[NSError alloc] init];
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Run Code Online (Sandbox Code Playgroud)

它会在日志中引发跟随错误

[NSError init] called; this results in an invalid NSError instance. It will raise an exception in a future release. Please call errorWithDomain:code:userInfo: or initWithDomain:code:userInfo:. This message shown only once.
Run Code Online (Sandbox Code Playgroud)

也许,你会告诉我答案在日志中,但我不明白如何初始化NSError.

tro*_*foe 11

您不能通过以下方式创建NSError实例-init; 使用-initWithDomain:code:userInfo:替代或构造方法+errorWithDomain:code:userInfo:.

在你的情况下,它是多余的,因为该方法将在出错的情况下创建它.

这是使用它的正常模式:

NSError *error = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request
                                      returningResponse:&response
                                                  error:&error];
if (!urlData) {
    NSLog(@"Error: %@", [error localizedDescription]);
    return NO;
}

// Successful
Run Code Online (Sandbox Code Playgroud)