Why [[NSError alloc] init]; to output error in Xcode?

I have code in Xcode:

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

And it causes the 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.

You might tell me that the answer is in the log, but I don't understand how to trigger NSError.

+4
source share
4 answers

You are not allowed to instantiate NSErrorthrough -init; use -initWithDomain:code:userInfo:or constructor method +errorWithDomain:code:userInfo:.

In your case, this is redundant, since this method will create it in case of an error.

This is a normal template to use it:

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

// Successful
+9
source

, . NSError *, nil. , . , NSError, - . , ,

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

NSError Cocoa , NSError - , , . . , , , , == nil.

+1

:

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

NSError *error = nil;
+1

, errorWithDomain:code:userInfo: initWithDomain:code:userInfo:.

Use is -[NSError init]not recommended and may cause an exception in a future version.

Screenshot for warning

Screenshot to use 1

Screenshot to use 2

Example:

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

Source: https://habr.com/ru/post/1615956/


All Articles