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
2010-05-24 20:20:42
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
2010-05-24 20:28:37
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
2010-05-24 21:06:25
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
2010-05-24 21:35:08
+2
A:
- (void) myMethod:(Parameter *)aParameter {
if (aParameter == nil) {
...
} else {
...
}
}
Elsewhere:
[anObject myMethod:foo];
Or:
[anObject myMethod:nil];
Dave DeLong
2010-05-24 20:21:32
Thanks, and an upvote for the code example. @kubi gets the check mark for beating you by less than a minute.
Dan Ray
2010-05-25 12:19:21