can we override alloc and dealloc in objective C?
I know that this is rarely required to override the alloc
or dealloc
methods,开发者_如何学运维but if required is it possible in iPhone programming?
You can and indeed, you should (if using manual memory management) override dealloc
to release any resources you hold (not forgetting to call [super dealloc]
when finished). Overriding alloc
is possible but, as you say, rarely needed.
In general, overriding alloc
is only done when you wish to, eg, allocate an object from a pool of available instances, or perhaps allocate a variable amount of storage for the object based on some external parameter. (In C++ you can access the new
parameters and allocate based on them, but Objective-C does not give you access to the initXXX
parameters.)
I've never attempted any of this, and I suspect that its a bit of a minefield -- you need to study up on the structures and be pretty careful.
As Adam said, you should ALWAYS (in a reference counted environment) override dealloc
if there are any retained objects held by your object.
Update: An interesting thing you can do ... in RedClass or a superclass of it code something like:
+(id)alloc {
if (self == [RedClass class]) {
return [BlueClass alloc];
}
else {
return [super alloc];
}
}
The net result is that whenever you execute [RedClass alloc]
a BlueCLass object will be returned. (NB: Presumably BlueClass is a subclass of RedClass, or things will get seriously mucked up shortly after the object is returned.)
Not saying that it's a good idea to do this, but it's possible (and I don't offhand know of any cases where it wouldn't work reliably for vanilla user-defined classes). And it does have a few possible uses.
Additional note: In some cases one might want to use [self isSubclassOf:[RedClass class]]
rather than ==
(though that has some serious pitfalls).
精彩评论