Unified Type/class

Jonathan Hogg jonathan at onegoodidea.com
Sun Jan 27 09:08:38 EST 2002


On 27/1/2002 12:04, in article
pan.2002.01.27.13.04.36.472022.1642 at club-internet.fr, "Pedro Rodriguez"
<pedro_rodriguez at club-internet.fr> wrote:

> If you have :
>   Foundation  
>       |
>       V
>     AppKit <- LoadingWidget Support
> Why is this support considered as part of the foundation ?

[Caveat: I'm still learning Objective-C.]

ObjC categories are effectively additional methods to an existing class
which are linked into that class if you link with the code containing the
category.

For instance (not a real example): if the Foundation classes didn't support
serialising and de-serialising themselves to a file, but the AppKit required
this, then you can either:

 1. Wrap all of the foundation classes in your own. Which is ugly.

 2. Write a bunch of functions and remember to explicitly call them when
    you want to serialise and de-serialise a Foundation object. Which is
    uglier, and defeats the purpose of OO.

 3. Write a category for serialising and de-serialising and "attach" it to
    the Foundation classes. All instances of the original classes
    immediately gain the new methods.

Categories are even more magic than this though, as subclasses of a class
with a category will also inherit the category. So if I write serialisation
methods for NSString and attach them as a category, then they also become
methods of NSMutableString.

This is more useful than it might at first seem if you're used to C or C++,
since the serialise method can ask the runtime system for the name of the
class of 'self' and serialise this too. Then the deserialise method can ask
the runtime for the class with that name, allocate an instance of it and
initialise it with the saved text. [All subclasses of NSString inherit its
initialisers and must guarantee to do something sensible with them.]

If you attach a category to the root class NSObject, then *all* instances of
*all* classes gain those methods.

ObjC really is a very whacky language much more akin to Python than C++.

Jonathan




More information about the Python-list mailing list