I tried something along the lines of:
if(myString != nil && myString.length) { ... }
And got:
-[NSNull length]: unrecognized selector sent to instance
Does Objective-C not short-circuit after the first condition fails?
In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point – they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument.
So when Java finds the value on the left side of an || operator to be true, then Java declares the entire expression to be true. Java's && and || operators use short circuit evaluation.
Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.
In C++, both && and || operators use short-circuit evaluation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With