tags:

views:

233

answers:

4

Is it better practice to use id or NSSomeObject * when possible? I know the compiler can do better checking when it's explicit, but I was just wondering which is better practice.

E.g.:

- (IBAction)someButton:(id)sender

vs.

- (IBAction)someButton:(NSButton *)sender.

Are there any benefits to either of those?

A: 

If you use - (IBAction)someButton:(id)sender, you could have an NSNotification or other event call this as a selector. Whereas, in your second case, only an NSButton * will be able to use this method.

As to whether allowing multiple object types to call an action is a good practice, I'm not positive. But I use it because I can write and debug less code.

Alex Reynolds
Not true. If you leave the declaration as NSButton*, the compiler will warn if you try to pass an object instance of a different type, but because Objective-C methods are late-bound, any object that responds to the appropriate selectors (methods) will work at run time.
Barry Wark
You don't need to actually to pass self as the argument for an IBAction — it's just a normal argument. Heck, in most cases, you can just pass nil as the sender anyway.
Chuck
+1  A: 

I like to use the specific classes.

Objective-C doesn't enforce you to write the correct type beacuse it's a dynamic language, but the compiler can warn you about some obvious errors.

Additionally, properties from Objective-C 2.0 do not work with the id type.


In your specific example with the IBAction I'd use id, because an action should be callable from anything, not only from buttons.

Georg
A: 

I know the compiler can do better checking when it's explicit, but I was just wondering which is better practice.

Static typing (= naming the precise type of your object) is your friend. When the compiler can do better checking, it will catch more errors for you. Only when you find yourself too restricted by static typing, use the id type (= duck typing).

zoul
Both of the answers above provide reasons to use (id) rather than a specific object type.
Matthew Schinckel
Sure. I just said that it is best to use static typing, until you have a good reason to do otherwise.
zoul
A: 

It is best practice to use the most explicit type possible specifically so that the compiler can help you catch the most basic mistakes. The safety you gain is really minimal, however. It is much more important that you have adequate unit tests to catch higher-level errors that would cause you to pass an unexpected instance type to the method.

Barry Wark