In the general case, alloc
overrides only when you want, for example, to allocate an object from the pool of available instances or, possibly, allocate variable memory for the object based on some external parameter. (In C ++, you can access the new
parameters and distribute them based on, but Objective-C does not give you access to the initXXX
parameters.)
I have never tried any of this, and I suspect this is a bit of a minefield - you need to learn from structures and be very careful.
As Adam said, you should ALWAYS (in a reference-counting environment) redefine dealloc
if there are any stored objects held by your object.
Update: An interesting thing you can do ... in RedClass or the superclass of this code is something like:
+(id)alloc { if (self == [RedClass class]) { return [BlueClass alloc]; } else { return [super alloc]; } }
The end result is that whenever you execute [RedClass alloc]
, the BlueCLass object will be returned. (NB: Presumably, BlueClass is a subclass of RedClass, or something will be seriously launched shortly after the object returns.)
Not to say that this is a good idea, but it is possible (and I donβt know of any cases when it would not work reliably for varied custom classes). And this has several possible uses.
Note: In some cases, you can use [self isSubclassOf:[RedClass class]]
rather than ==
(although this has some serious problems).
source share