Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

Does Objective-C use short-circuit evaluation?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...