Does Objective-C use short-circuit evaluation?

前端 未结 4 2016
庸人自扰
庸人自扰 2020-12-01 16:26

I tried something along the lines of:

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

And got:

-[NSNull length]: unrecognize

4条回答
  •  悲&欢浪女
    2020-12-01 16:47

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

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

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

    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.

提交回复
热议问题