Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a need for a class to override +alloc in Objective-C?

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?

like image 869
Rob Jones Avatar asked Sep 03 '09 04:09

Rob Jones


3 Answers

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.

like image 98
Ken Avatar answered Nov 15 '22 13:11

Ken


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

like image 22
Barry Wark Avatar answered Nov 15 '22 11:11

Barry Wark


I override alloc for Singleton classes, e.g.:

#import "Singleton.h"

static Singleton * instance;

@implementation Singleton

+ (void)initialize
{
    if (!instance) {
        instance = [[super allocWithZone:NULL] init];
    }
}

+ (id)allocWithZone:(NSZone * const)notUsed
{
    return instance;
}

@end
like image 38
Howard Lovatt Avatar answered Nov 15 '22 12:11

Howard Lovatt