Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

nserror

alloc

I have the following code in Xcode :

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

And it throws following error in the logs

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

Maybe, you will tell me that the answer is in the log, but I do not understand how to init NSError.

like image 986
Ludo Avatar asked Nov 15 '15 13:11

Ludo


3 Answers

You are not allowed to create an NSError instance via -init; use -initWithDomain:code:userInfo: instead or the constructor method +errorWithDomain:code:userInfo:.

In your case it's redundant anyway as that method will create it in the case of error.

This is the normal pattern for using it:

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

// Successful
like image 100
trojanfoe Avatar answered Oct 24 '22 05:10

trojanfoe


Think about what you are doing. You should initialise an NSError* variable by setting it to nil. You don't even have to do that, the compiler does it for you. Initialising it by creating a new NSError object is nonsense. It's the same nonsense that you often see when beginners write

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

In the case of NSError, Cocoa rightfully tells you that creating an NSError object without any error information is nonsense and therefore a bug. But there is not the slightest need to do this. Actually, it would break the line that you missed out where you check if error == nil.

like image 40
gnasher729 Avatar answered Oct 24 '22 06:10

gnasher729


I solved it replacing:

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

to

NSError *error = nil;
like image 1
javaboygo Avatar answered Oct 24 '22 06:10

javaboygo