Can we override alloc and dealloc in a C object?

I know that it is rarely required to redefine the alloc or dealloc methods, but if necessary, is this possible in iPhone programming?

+6
source share
2 answers

You can and really, you must (when using manual memory management) redefine dealloc to free up all your resources (remember to call [super dealloc] at the end). Overriding alloc possible, but, as you say, is rarely required.

+13
source

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).

+6
source

Source: https://habr.com/ru/post/898278/


All Articles