I am trying to change the class of objects created using the tip with the iPhone SDK.
The reason for this is; I still don't know what the class I want the nib object to be (although they will have the same superclass of the UIView class), and I don't want to create a different thread for each case - since .nib will be the same for everyone except class of one object.
I was successful with several methods, but either had some knocking on effects, or was not sure how safe the methods I used were:
Method 1: override alloc in the superclass and set the variable c to the class I need:
+ (id) alloc {
if (theClassIWant) {
id object = [theClassIWant allocWithZone:NSDefaultMallocZone()];
theClassIWant = nil;
return object;
}
return [BaseClass allocWithZone:NSDefaultMallocZone()];
}
this works well, and I assume that it is “reasonably” safe, although if it has zero with the correct class as the class identifier in Nib, or I subclasses myself (without setting theClassIWant), an object is created in the base class. I also don't like the idea of overriding alloc ...
Method 2: use object_setClass (self, theClassIWant) in initWithCoder (before calling initWithCoder in the superclass):
- (id) initWithCoder:(NSCoder *)aDecoder {
if (theClassIWant) {
object_setClass(self,theClassIWant);
theClassIWant = nil;
return [self initWithCoder:aDecoder];
}
if (self = [super initWithCoder:aDecoder]) {
...
this also works well, but not all subclasses will necessarily be the same size as the superclass, so this can be very dangerous! To combat this, I tried to free and redistribute the correct type in initWithCoder, but I got the following error from the framework:
"This encoder requires replaced objects to be returned from initWithCoder:"
I don’t understand what that means! I am replacing an object in initWithCoder ...
!