我在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。
答案 0 :(得分: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
答案 1 :(得分:1)
想想你在做什么。您应该通过将NSError *变量设置为nil来初始化它。您甚至不必这样做,编译器会为您完成。通过创建新的NSError对象来初始化它是无稽之谈。这与你在初学者写作时经常看到的一样废话
NSArray* array = [[NSArray alloc] init];
array = ...;
在NSError的情况下,Cocoa正确地告诉您创建一个没有任何错误信息的NSError对象是无意义的,因此是一个错误。但是没有丝毫需要这样做。实际上,它会打破你错过的线,你检查错误== nil。
答案 2 :(得分:1)
我解决了它取代:
NSError *error = [[NSError alloc]init];
到
NSError *error = nil;
答案 3 :(得分:0)
日志本身声明您应该使用errorWithDomain:code:userInfo:
或initWithDomain:code:userInfo:
来解决此问题。
不建议使用-[NSError init]
,这可能会在将来的版本中引起异常。
示例:强>
NSError *errMsg = [NSError errorWithDomain:@"domain" code:1001 userInfo:@{
NSLocalizedDescriptionKey:@"Localised details here" }];
答案 4 :(得分:-1)
在 Swift 中
我解决了这个问题
let error : NSError? = nil