繁体   English   中英

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

[英]Get rid of warning “Expression Result Unused”

我有以下几行代码:

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

在最后一行,我得到“表达结果未使用”警告。 现在,根据我在网上阅读的所有文章,这是调用方法的正确方法,建议语法下载URL异步。 如何重写此代码以修复警告?

问题来自于NSURLRequest initWithRequest…方法NSURLRequest initWithRequest…返回一个你不存储的对象。

如果你不需要它,你应该写:

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

在Xcode上,您也可以使用限定符__unused来丢弃警告:

__unused [connection initWithRequest:request delegate:self];

通知编译器您故意要忽略返回的值。

你可以使用这一行:

 [NSURLConnection connectionWithRequest:request delegate:self];

代替:

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

有关所有Clang警告的列表,您可以在此处查看

将最后两行替换为:

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

警告很有用,因为alloc可以返回与init不同的对象(例如,当您使用NSArray ,它使用类集群模式 )。

在这种情况下, connection将是对alloc返回的这个“中间”对象的引用,而不是init返回的完全初始化的实例。

只需将最后一行更改为:

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

暂无
暂无

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

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