iosnserroralloc

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


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.


Solution

  • 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