tags:

views:

159

answers:

2

Hei,

I have this code:

- (BOOL)isConnected { return !!_sessionKey; }

where _sessionKey is defined earlier as:

NSString* _sessionKey;

the code comes from the facebook-connect for iphone.

Since I am learning Objective-C by looking at code written by other people. The !! used in the isConnection function seems useless to me, or am I missing something? What does it do?

+7  A: 

It means "not not".

In this case, the first ! could be interpreted as "doesn't exist", so it means if (not doesn't exist sessionKey).

It's basically a short way to say

return (_sessionKey != nil).
Benjamin Cox
+6  A: 

The !! converts the result to either YES or NO.

Using !!x is an idiom from C. The result of this expression is:

  • !!x == 0 when x == 0 // x is zero
  • !!x == 1 when x != 0 // x is non-zero

At least in C, you can use any non-zero expression as a value which satisfies the condition of an if () or other conditional control flow. However, sometimes it is nice to know that the "true value" is represented by 1 rather than merely "non-zero".

In Objective-C, YES is defined as 1 rather than as "non-zero". Thus, in Objective-C, this C idiom becomes more useful.

Another way of putting it:

  • !!x == NO when x == NO
  • !!x == YES when x != NO
Heath Hunnicutt
In this case, since _sessionKey appears to be an object, 0 is equivalent to 'nil'. And, since it's Objective-C, the result is YES or NO, rather than 0 or 1. Sorry if I'm just pickin' the fly dung out of the pepper here.
Benjamin Cox
Absolutely, I did add that. Benjamin, notice it's a community wiki. Feel free to add to it.
Heath Hunnicutt
What nobody seems to have explicitly pointed out so far: `!!` is not, itself, an operator. It's just the `!` operator applied twice.
Nefrubyr