Re: Convenience Methods
Re: Convenience Methods
- Subject: Re: Convenience Methods
- From: Alastair Houghton <email@hidden>
- Date: Wed, 26 Sep 2007 12:03:26 +0100
On 26 Sep 2007, at 03:59, Jeff Laing wrote:
There is no way the class method is going to return subclasses.
Yes there is.
No there isn't.
Actually it depends.
If you call [MySubclass repoWithName:…] you'd get an instance of
MySubclass. You don't need to override the class method for it to do
this.
Yes, you called some other class method, not the one being discussed.
It depends on whether the method does
[[self alloc] initWithName:...]
or
[[MyClass alloc] initWithName:...]
In the former case, you'd get an instance of the subclass, in the
latter of the original class. Both styles are in use in Cocoa programs.
But, nevertheless, Jeff is right (in his other posts) that a subclass
is also a valid instance of its superclass, so in a sense this is
(sometimes) irrelevant. Also, I don't think the compiler checks that
the method signatures are identical (unlike in C++, where this is a
requirement), so you can probably just declare the class method
differently in your subclass. This makes sense, because (after all)
you're normally writing
[MyClass repoWithName:@"Foo"]
or [MySubclass repoWithName:@"Foo"]
rather than
[someClass repoWithName:@"Foo"]
(which I'd probably write in full as [[someClass alloc]
initWithName:@"Foo"]).
Another downside of using id is that it means that the compiler
sometimes has to guess which method you mean. For instance, if you
make a method called -size that returns (e.g.) a size in bytes, and
you call it via an id, you'll probably find that the compiler thinks
it should return an NSSize and not whatever your actual method
returns. That's because it doesn't know the type, so it looks
through the messages it knows about and the first one it finds called
"size" happens not to be the one you declared. (I've had this happen
on a couple of occasions... I'm sure I even managed to cause a bug
somewhere because of this "guessing" behaviour, though I don't
remember the details).
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden