Objective-C是否使用短路评估? [英] Does Objective-C use short-circuit evaluation?
问题描述
我尝试了以下方法:
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.
在您的示例中,似乎myString
是NSNull
而不是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屋!