tags:

views:

35

answers:

2

How do I spell a method whose argument can either be an object of a certain type, or nil? You see those all the time in framework classes, but I've just encountered my first instance where it would be useful to create one.

+2  A: 

You can always pass nil instead of an object, there's nothing special you need to specify.

kubi
That's hilarious. I assumed I'd have to notify obj-c in triplicate, like so many other parts of the language. No wonder I couldn't find that documented anywhere!
Dan Ray
The constant `nil` is defined as `(id)0` — so it is an object, and thus can be passed to most methods that take objects. (Some methods disallow nil, but *that* is the exception to the rule. For example, NSArray can't contain nil, so attempting to add nil to an array will create an exception.)
Chuck
As a side-note, that's nothing to do with the way `-addObject:` or similar is declared; the implementation simply checks whether the object passed in is `nil` and if so throws an exception. Passing `nil` as a parameter to the method is – from the language perspective – still perfectly valid.
Perspx
+2  A: 
- (void) myMethod:(Parameter *)aParameter {
  if (aParameter == nil) {
    ...
  } else {
    ...
  }
}

Elsewhere:

[anObject myMethod:foo];

Or:

[anObject myMethod:nil];
Dave DeLong
Thanks, and an upvote for the code example. @kubi gets the check mark for beating you by less than a minute.
Dan Ray