Why cannot we use the negation operator when checking for the existence of a symbol?

171 views Asked by At

The answers to this question state that if (x != nil) is the same as if (x).

But Apple documentation reads:

Note: When checking for the existence of a symbol, you must explicitly compare it to NULL or nil in your code. You cannot use the negation operator ( ! ) to negate the address of the symbol.

Which seems to contradict "Working with nil" from https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4-SW22

2

There are 2 answers

8
rmaddy On

The documentation is stating that you can't negate the address. In other words, you can't do this:

if (!MyWeakLinkedFunction) {
    // symbol doesn't exist
}

You must instead do:

if (MyWeakLinkedFunction == NULL) {
    // symbol doesn't exist
}

However, both of these work:

if (MyWeakLinkedFunction) {
    // symbol exists
}

or:

if (MyWeakLinkedFunction != NULL) {
    // symbol exists
}
0
Rajeev Ranjan On

IMO, we might just be overthinking.

When checking for the existence of a symbol, you must explicitly compare it to NULL or nil in your code.

This part only says - If you want to check for the existence(and not the non-existence), you must explicitly compare to NULL or NIL

You cannot use the negation operator ( ! ) to negate the address of the symbol.

If you succeed negating the address of the symbol, its only that you land up successfully checking the non-existence(and not the existence).

When i came across the following, I thought this might be a possibility as they use the word availability here -

Note: To check the availability of a function, explicitly compare its address to NULL or nil. You cannot use the negation operator ( ! ) to negate the address of a function to check its availability. Also, note that the name of a C function is synonymous with its address. That is, &myFunction is equivalent to myFunction.