Objective-C是否使用短路评估? [英] Does Objective-C use short-circuit evaluation?

查看:78
本文介绍了Objective-C是否使用短路评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下方法:

if(myString != nil && myString.length) { ... }

得到了:

-[NSNull长度]:无法识别的选择器已发送到实例

-[NSNull length]: unrecognized selector sent to instance

在第一个条件失败后,Objective-C不会短路吗?

Does Objective-C not short-circuit after the first condition fails?

推荐答案

与C一样,Objective-C确实支持短路评估.

Objective-C does support short-circuit evaluation, just like C.

在您的示例中,似乎myStringNSNull而不是nil,因此myString != nil是正确的.

It seems that in your example myString is NSNull and not nil, therefore myString != nil is true.

NSNull 是单例,用于表示仅允许对象(例如在NSArray中)的nil.

NSNull is a singleton and is used to represent nil where only objects are allowed, for example in an NSArray.

顺便说一句,通常人们会写if (!myString && myString.length == 0).与nil相比是非常丑陋的.另外,我将长度与0进行比较.这似乎更加清楚.

Btw, normally, people write if (!myString && myString.length == 0). Comparing to nil is quite ugly. Also, I'd compare the length to 0. That seems to be more clear.

这篇关于Objective-C是否使用短路评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆