[Biococoa-dev] More on BCSymbolSets

Charles PARNOT charles.parnot at stanford.edu
Thu Mar 3 01:04:04 EST 2005

>Incidentally, how does ObjC work:  you have a pointer typed to one thing,
>and it actually holds a subclass - when you request its class, what do you

I forgot to answer that earlier.

ObjC is dynamic. When you send the message class to an object at runtime, you are actually asking the runtime to take whatever pointer is hold by the variable and get the struct pointed by that reference. Normally, this struct should be an object with all its ivars, including all the ivars from all the superclasses, such as the ivar 'isa' (if the pointer does not point to a struct for an object). This ivar 'isa' points to another struct, which is the class object. The class object can then be used to find the pointer to the function actually implementing the method with selector 'class', starting with the subclass, and going up in the class tree until it finds a class object that does implement the selector. That function is then called. In the case of 'class', NSObject implements it. I don't know what the code is, but it probably simply returns the 'isa' value.

In summary, because it is dynamic, you always get the real class at runtime (except if you override the method 'class' to return junk!). For instance:
NSArray *anArray=[NSString stringWithString:@"a string"];
NSLog(@"%@ : %@",[anArray class],anArray);

---> 'NSString : a string'

and does not give any compiler warning(!!) because the type returned by 'stringWithString' is an id. In other words, the compiler can check typing, but will not if you use id. Depending on the situations, you thus may have a compiler warning and no runtime error, and you may have no compiler warning but a runtime error, just because the type of an object as guessed by the compiler may be different at runtime. This is also what my placeholder sequence class BCSequence does.

Another little comment on the 'class' method. This is something quite important to remember to use in some occasions, for instance when you write a 'copy' method. You should always use [[self class] alloc] instead of [className alloc] if you need to create a new instance that will be the copy. This is in case the method is actually run for an instance of a subclass. Otherwise, you get an instance of the superclass when calling copy on an instance of a subclass (and if this subclass does not override the copy method). This might be the case for the sequence class tree, where we may be able to have the copy in the superclass, without overriding in the subclasses.

Help science go fast forward:

Charles Parnot
charles.parnot at stanford.edu

Room  B157 in Beckman Center
279, Campus Drive
Stanford University
Stanford, CA 94305 (USA)

Tel +1 650 725 7754
Fax +1 650 725 8021

More information about the Biococoa-dev mailing list