EDITED FOR TYPO -
How can I check one thing AND THEN another, if the first is true?
For example, say I have a shopping basket object, and I only want to do something if the basket has been created AND it isn't empty.
I've tried:
if ((basket) && ([basket numberOfItems] >0))...
But the second condition is evaluated even if the first fails, resulting in a crash (presumably because i'm calling numberOfItems on an object that doesn't exist).
I can nest them, but this seems a bit ugly, and more to the point is problematic. Say I want to do one thing if the basket exists AND isn't empty, but another if either isn't true. That doesn't really work well in nested if statements.
If Objective-C is a strict superset of C (which, in my understanding, it is), then boolean evaluation short circuits with the && and || operators. This means that since you're using &&, as soon as a condition fails, the remaining conditions are not even evaluated.
Given your code, that means that if the object is null, then the message is never dispatched.
Your understanding is not correct; the && operator does "short circuit" the way that you want. Your problem is somewhere in your own code.
If the crash is really on this line, then:
basket pointer is not nil. If it were, the call to numberOfItems would do nothing and return NO, which is the default behavior for messaging nil (not crashing).basket might have been an object once, that's already been dealloced by this point, and is now blowing up on sending it a message. basket might be some other (non-nil) garbage pointer. In this case or the one above, you'd probably see EXC_BAD_ACCESS in the debugger.basket might not support a numberOfItems method. This usually is made quite explicit in the debugger.If the crash is possibly not on this actual line, then something else could be up, too.
(updated per OP update & helpful comments)
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