Reputation: 65479
Is there a way to shorten this if statement ?
if(objectA != objectD && objectB != objectD && objectC != objectD)
something like this pseudo code:
if(objectA && objectB && objectC != objectD)
EDIT:
and what if i only want to check if it is not NULL? Something like:
if(objectA != NULL && objectB != NULL && objectC != NULL)
EDIT 2 (sorry):
and what if i only want to check if it is not NSNull?
if(objectA != [NSNull null] && objectB != [NSNull null] && objectC != [NSNull null])
Upvotes: 1
Views: 364
Reputation: 9235
NULL
, nil
and 0
are technically the same:
From MacTypes.h
#ifndef NULL
#define NULL __DARWIN_NULL
#endif /* ! NULL */
#ifndef nil
#define nil NULL
#endif /* ! nil */
And you can verify that NULL
is some variation of 0
by fishing through the header files like stddef.h
.
So to ensure they all exist, to just test for NULL
, or more accurately, since these are objects, nil
:
if (objectA && objectB && objectC) ...
But, IMO, you shouldn't do this unless you need to act on the fact that they're nil
. Since nil
accepts messages, it can often be better to structure your code so that nil
can be a valid receiver. That is, if nothing happens when sending messages to these nil
objects, it doesn't cause any problems. In other words, consider not using nil
as an error case but rather return a *NSError
from APIs that can fail.
With respect to the NSNull issue specifically, I wrote an example of how to simplify code using variadic functions. It'll allow you to write:
if (isNSNull(objectA, objectB, objectC, objectD, nil)) ...
to test whether all the objects == [NSNull null]
. You can also use a similar technique to test if they are all the same object:
if (isEqualTo(objectD, objectA, objectB, objectC, nil)) ...
will return YES
if A, B, and C are all ==
to D.
The crux of the example is:
// This is just a simple object equality comparator.
static NSComparator compareeq = ^(id obj1, id obj2) {
if (obj1 == obj2) {
return (NSComparisonResult)NSOrderedSame;
}
return (NSComparisonResult)NSOrderedDescending;
};
// This'll execute the above comparator to compare eq to each object in args
NSComparisonResult comparatorV(NSComparator compare, NSObject *eq, va_list args) {
NSComparisonResult result;
NSObject *value;
do {
if (value = va_arg(args, NSObject*)) {
result = compare(eq,value);
}
} while (value && result == NSOrderedSame);
return (!value?NSOrderedDescending:NSOrderedSame);
}
// This just test if each object passed is == [NSNull null].
BOOL isNSNull(NSObject *o, ...) {
NSNull *n = [NSNull null];
if (NSOrderedSame != compareeq(n,o)) return NO;
va_list args;
va_start(args, o);
BOOL result = (NSOrderedSame != comparatorV(compareeq,n,args));
va_end(args);
return result;
}
Upvotes: 2
Reputation: 7510
If you want to check if three objects (a, b, and c) are equal to object D, you may be able to do the following:
if (objectA == objectB == objectC == objectD) {
// .. your code here ..
}
Upvotes: 0