Get rid of the warning "Expression result is not used"

I have several lines of code:

NSURL *url = [NSURL URLWithString:URL];
NSURLRequest* request = [NSURLRequest requestWithURL:url .... ];
NSURLConnection* connection = [NSURLConnection alloc];
[connection initWithRequest:request delegate:self];

      

On the last line, I get an "Unused Expression Result" warning . Now, according to all the articles online I've read, this is the correct way to call the method and the syntax is recommended to load the async url. How can I rewrite this code to fix the warning?

+3


source to share


5 answers


You can use this line:

 [NSURLConnection connectionWithRequest:request delegate:self];

      



instead:

NSURLConnection* connection = [NSURLConnection alloc];
[connection initWithRequest:request delegate:self];

      

+3


source


The problem arises because the method NSURLRequest initWithRequest…

returns an object that you are not storing.

If you don't need it, write:



(void)[connection initWithRequest:request delegate:self];

      

tell the compiler that you intentionally want to ignore the return value.

+5


source


#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
NSURL *url = [NSURL URLWithString:URL];
NSURLRequest* request = [NSURLRequest requestWithURL:url .... ];
NSURLConnection* connection = [NSURLConnection alloc];
[connection initWithRequest:request delegate:self];
#pragma clang diagnostic pop

      

A list of all Clan warnings can be suppressed here

+1


source


Replace the last 2 lines:

connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

      

The warning is useful because it alloc

may return a different object than init

(for example, when you are using NSArray

that uses a class cluster template ).

In this case, it connection

will be a reference to this "intermediate" object returned alloc

instead of the fully initialized instance returned init

.

+1


source


Just change the last line to:

connection = [connection initWithRequest:request delegate:self];

+1


source







All Articles