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

Why does [[NSError alloc] init]; in Xcode throw an error?

我在 Xcode 中有以下代码:

NSError *error = [[NSError alloc] init];
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

它在日志中抛出以下错误

[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.

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

您不能通过 -init 创建 NSError 实例;使用 -initWithDomain:code:userInfo: instead or the constructor method +errorWithDomain:code:userInfo:.

在你的情况下,无论如何它都是多余的,因为该方法会在出错的情况下创建它。

这是使用它的正常模式:

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

// Successful

想想你在做什么。您应该通过将其设置为 nil 来初始化 NSError* 变量。您甚至不必这样做,编译器会为您完成。通过创建一个新的 NSError 对象来初始化它是无稽之谈。和初学者写的时候经常看到的一样的废话

NSArray* array = [[NSArray alloc] init];
array = ...;

在 NSError 的情况下,Cocoa 正确地告诉您创建一个没有任何错误信息的 NSError 对象是无稽之谈,因此是一个错误。但丝毫没有必要这样做。实际上,它会打破您在检查错误 == nil 时遗漏的行。

我解决了它替换:

NSError *error = [[NSError alloc]init];

NSError *error = nil;

日志本身指出您应该使用 errorWithDomain:code:userInfo:initWithDomain:code:userInfo: 来解决此问题。

不推荐使用 -[NSError init],它可能会在未来的版本中导致异常。

示例:

    NSError *errMsg = [NSError errorWithDomain:@"domain" code:1001 userInfo:@{  
                      NSLocalizedDescriptionKey:@"Localised details here" }];

在Swift

我解决了这个问题

 let error : NSError? = nil

对 Swift

中的 NSError 使用以下代码
let error = NSError(domain: "", code: 101, userInfo: [ NSLocalizedDescriptionKey: "error in download"])

并使用这个错误

  print("Domain : \(error.domain)")
  print("code : \(error.code)")
  print("Description : \(error.localizedDescription)")