简体   繁体   English

摆脱警告“表达结果未使用”

[英]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. 现在,根据我在网上阅读的所有文章,这是调用方法的正确方法,建议语法下载URL异步。 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. 问题来自于NSURLRequest initWithRequest…方法NSURLRequest initWithRequest…返回一个你不存储的对象。

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: 在Xcode上,您也可以使用限定符__unused来丢弃警告:

__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 有关所有Clang警告的列表,您可以在此处查看

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 ). 警告很有用,因为alloc可以返回与init不同的对象(例如,当您使用NSArray ,它使用类集群模式 )。

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将是对alloc返回的这个“中间”对象的引用,而不是init返回的完全初始化的实例。

只需将最后一行更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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