简体   繁体   中英

Get rid of warning “Expression Result Unused”

I have the following few lines of code:

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

In the last line I get "Expression Result Unused" warning. Now, according to all the articles online I have read, this is the correct way to call a method, and the syntax is as advised to download a URL async. How to rewrite this code to fix the warning?

The problem comes from the fact that method NSURLRequest initWithRequest… return an object that you don't store.

If you don't need it, you should write:

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

On Xcode, you can use qualifier __unused to discard warning too:

__unused [connection initWithRequest:request delegate:self];

to inform the compiler that you deliberately want to ignore the returned value.

You can use this line:

 [NSURLConnection connectionWithRequest:request delegate:self];

instead of:

NSURLConnection* connection = [NSURLConnection alloc];
[connection initWithRequest:request delegate:self];
#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

For a list of all the Clang Warnings you can suppress take a look here

Replace the last 2 lines with:

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

The warning is useful because alloc can return a different object than init (for example, when you use NSArray , which employs class cluster pattern ).

In that case connection would be a reference to this "intermediate" object returned by alloc instead of a fully initialized instance returned by init .

只需将最后一行更改为:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM