Re: how to centralize functionality more elegantly?
Re: how to centralize functionality more elegantly?
- Subject: Re: how to centralize functionality more elegantly?
- From: Andy Lee <email@hidden>
- Date: Sat, 7 Sep 2002 13:59:29 -0400
At 6:02 PM +0200 9/7/02, Ondra Cada wrote:
And since -delegate returns an id, you can send it *any* message
without a warning.
Actually that is not *quite* true. You can send an id any message
the compiler has seen declared for any class. The compiler knows the
message is valid for *some* class and trusts you to make sure the
object is an instance of such a class at runtime.
If you try making up a nonsense message name and sending it to an id
you will get a warning.
The cast has its use though -- it would never get rid of any
warning; quite the opposite: it would *cause* a warning in case you
send a message for which the MainController has no method (more
precisely, which is not declared in its interface).
Yup. For this reason I think it's a good practice to use a cast (or
assign to a typed variable) before sending a message to an id.
Another example is when looping through a collection using
-nextObject:. By forcing yourself to state what you think the object
is, you add a sanity check to your code ("Oops, I meant
-setStringValue:, not -setString: -- good thing the compiler warned
me!"). You also help whoever reads your code to understand your
intentions. It also helps to name id variables appropriately, but
you don't always have a variable -- you may only have an expression
like "[NSApp delegate]".
Sometimes there is no common subclass that you can cast the id to,
other than NSObject, which doesn't help. In such cases you may want
or need to test the object with -respondsToSelector: or
-isKindOfClass:, or it may be okay to just take your chances that the
id will respond to the message you send, because you're pretty sure
the object will be what you think it is.
--Andy
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.