views:

171

answers:

2

Based on some answers to this question it appears that +alloc does some behind-the-scenes magic to allocate memory for an instance of an object in Objective-C. Is there ever a need to override +alloc?

+2  A: 

+alloc is not doing any magic, it is just calling a method in the Objective-C runtime to get the size of a class instance and allocating that amount of memory. You may want to override +alloc when writing a true singleton (i.e. you want to guarantee that only a single instance of your class can ever be allocated). Although it's rarely necessary to go to these lengths when writing a singleton class, you could. In general you would override +alloc to provide alternative (like not allocating memory in a different zone, allocating a different class than the receiving class--this is what class clusters might do) behavior or you might call +[super alloc] to do the standard work then add your own customizations.

Barry Wark
+4  A: 

It's quite rare.

NSString is an example of a class that overrides +alloc as an implementation detail. If you were to check, you'd find +[NSString alloc] returns something of class NSPlaceholderString. This is part of the implementation of the string class cluster.

You could also override to allocate from a different allocation NSZone be default. Or, you can play tricks like calling NSAllocateObject with something non-zero for extraBytes to provide a dynamic amount of space following your ivars. For example, you might think that the private subclass of NSString that you normally end up would look something like this:

@interface {
    NSUInteger length;
    unichar *data;
}

but that isn't the case. It's a single block of memory that contains both the length and the character data. Different NSString instances are different size blocks of memory. This is the kind of thing you can arrange by calling NSAllocateObject directly.

But all of these things are tricks and hacks. If you override +alloc, something special is going on.

Ken