Consecutive if statements
INVENTED FOR TYPO -
How can I check one AND THEN another if the first is true?
For example, let's say I have a shopping cart object and I only want to do something if the cart is created and it is not empty.
I tried:
if ((basket) && ([basket numberOfItems] >0))...
But the second condition is evaluated even if the first fails, which causes it to fail (presumably because I am calling numberOfItems on an object that doesn't exist).
I can nest them in the nest, but that seems a little ugly and problematic by the way. Let's say I want to do one if the basket exists AND is not empty, and another if it is incorrect. This doesn't work very well in nested if statements.
a source to share
If Objective-C is a strict superset of C (which I think it is), then boolean computes short-circuits with operators &&
and ||
. This means that since you are using &&
as soon as a condition fails, the rest of the conditions are not even evaluated.
Given your code, this means that if the object is null, the message is never sent.
a source to share
Your understanding is wrong; The && operator will short-circuit the way you want. Your problem is somewhere in your own code.
If the accident is indeed on this line, then:
- Pointer
basket
notnil
. If it did, the call wouldnumberOfItems
do nothing and returnNO
, which is the default messaging behaviornil
(not fail). -
basket
could be one of the objects that has already been freed from this point, and will now explode, sending him a message. -
basket
there may be some other (non-null) garbage pointer. In this case or higher, you will probably see EXC_BAD_ACCESS in the debugger. -
basket
may not support the methodnumberOfItems
. This is usually done pretty explicitly in the debugger.
If the accident may not be included in this real line, then something else may arise.
(updated on OP update and helpful comments)
a source to share
to expand on what others have said: && does short-circuit, but neither does. However, as others have said, in a C object, you can dispatch methods without error, so short-circuiting is not your problem. (I just mentioned and for completeness).
I think the most likely problem is that you created a bucket at some point and then released it, but never set it to zero ... so the bucket is not null, but it is also not a valid object. ..
it might help if you let us know what the actual error message was when it crashed ... My theory will give you an error message that says something about passing the message to an issued or garbage collector or something. ...
a source to share
if ((basket) && (basket numberOfItems> 0)) .....
or
if (cart! = null)
if the cart object is not created or not assigned to a value, then in this condition .... first it will check if there is a given value of the cart object .... only if it is true, then only it will check another condition ..... and if both truths, then only it will be that if part .....
a source to share