Re: Categories and adding instance variables
Re: Categories and adding instance variables
- Subject: Re: Categories and adding instance variables
- From: Glenn Andreas <email@hidden>
- Date: Sun, 01 Aug 2004 18:32:30 -0500
On Sunday, August 01, 2004, at 04:54PM, Kay Roepke <email@hidden> wrote:
>
On 1. Aug 2004, at 21:59 Uhr, Dennis C. De Mars wrote:
>
>
> The experts can address this more thoroughly, but I believe it is
>
> because there may be code that did not see the category, possibly
>
> compiled before you defined the category, and that code will allocate
>
> memory for the instance variables without allocating space for your
>
> new instance variable. Initialization is an issue also.
>
>
Aah, yes...adding methods probably just messes with some tables used to
>
look up the function pointers. But I was under the
>
impression that there was something called ivar lists. At least my
>
memory tries to convince me that I have seen such a thing in
>
some objc headers. I'll check.
Instance variables are accessed by offset, so there are two problems.
First, any object allocated before the category that would have new ivars would be the size of the old object, and not have space for the new ivars (which at best might cause a crash when you tried to access the ivars for a "pre-category" instance).
Second, subclasses would be totally hosed, since what use to be the first offset in the subclass would overlap with the "added" ivar from the category (and storing two different things in the same place is complete madness).
It is, however, possible to simluate this by providing accessor methods and a separate parallel data structure (usually a hash table that goes from the object to its ivar value). Reference counting does this - there is no "reference count" instance variable, but a map from all objects with a reference count > 1 to their "real' reference counts. So the code for NSObject "referenceCount" roughly is "if we are in the reference count table, use that value, otherwise we have a value of 1" (and dealloc removes this object from the dictionary as well - it actually a bit more subtle than this, but that's the general idea). This technique allows reference counting to be added to any object (i.e., there is a category of Object that add reference counting, and effectively adds the reference count "virtual ivar" to any object, regardless of what class it is).
Methods, on the other hand, are stored in a series of lists, and when a new category is added to the runtime, the methods for that category are added to the list of method lists (there's also a method dispatch cache that gets updated to reflect this as well).
All in all, the Objective-C runtime is pretty amazing - both very simple, yet very subtle and powerful.
_______________________________________________
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.