Objective-C simple type comparison chart

I’ve always been a fan of PHP’s type comparison tables, and today Aaron and I started talking about how you can write the following in objective-c, but not in java:

if ( myObject )

I started wonderring how this works. Is [myObject description] getting called behind the scenes here? (Spoiler: The answer is no.)

I built a quick project to figure out why this happens, and some of my results were surprising. Essentially, you should never write if ( myObject ), because it is probably not what you want. It’s basically always true unless you initialize your objects to nil. (I actually recall that auto-initialization of objects to nil was one of the new language features announced last week at WWDC.)

Here are my findings for the statement: if ( X )

nil false — Interestingly, this is defined like this:
#define nil NULL
NULL false — Defined as follows:
#define NULL ((void*)0)
MyObj *myObj; true — (In some brief googling, I couldn’t figure out whether this was random memory access, or just looking at the pointer itself.)
MyObj *myObj = nil; false
MyObj *myObj = [[[MyClass alloc] init] autorelease]; true
@"" true — This is just creating a new NSString
0 false
1 true
YES true — Definition: #define YES (BOOL)1
true true — Definition: #define true 1
TRUE true — Definition: #define TRUE 1

I learned something. I hope Aaron did too.

  1. No comments yet.

  1. No trackbacks yet.