Brandon
Brandon

Reputation: 23500

Allocate using #define

I created a preprocessor definition to allocate and construct classes for me as follows:

#define new(cls) cls* _new() {return [[cls alloc] init];}()

Now I tried using it like:

- (NSMutableArray*) stack
{
    if (!_stack)
    {
        /*_stack = [[NSMutableArray alloc] init];*/
        _stack = new(NSMutableArray);
    }
    return _stack;
}

but it says expected expression and unexpected NSMutableArray interface. What is wrong with my definition and why can't I do it? Is there another way I can do this?

Upvotes: 1

Views: 52

Answers (1)

zaph
zaph

Reputation: 112857

Just use new:

_stack = [NSMutableArray new];

which does the same thing as

_stack = [[NSMutableArray alloc] init];

No need for a macro which will be confusing to others.

For a long time the use of new was discouraged by Apple but it seems with the arrival of ARC it has come back into favor even in Apple's documentation.

Upvotes: 2

Related Questions