Purpose of using alloc in objective C

objective-c

Solution

`[NSNumber initWithInt:]` won't work, because `-initWithInt:` is an instance method and you're sending it to the class. `[NSNumber numberWithInt:]` will work, but that's (probably) a convenience wrapper around `[[NSNumber alloc] initWithInt:]`.

Foundation (and everything built on it, including UIKit and probably your own classes in an iOS app too) uses the two-stage creation technique. The `+alloc` method is just responsible for allocating enough memory for your instance and setting a pointer that says what class it's an instance of. Custom set-up can then be done in an `-init` (or `-init…`) method.

The advantage of this system is that your custom initialisers do not have to concern themselves with allocating memory for the object. The disadvantage is that client code has to call both stages, which is why convenience constructors like `+new` and `+numberWithInt:` are created.

At a more advanced level, the two-stage creation process is also used to support class clusters like `NSArray` and `NSNumber`, where the exact type to use is not known until the initialiser is called. `+alloc` can return a placeholder object that then replaces itself during the second stage.

Problem

What is the difference between ``` NSNumber *number = [[NSNumber alloc]initWithInt:13]; ``` and ``` NSNumber *number = [NSNumber initWithInt:13]; ``` Why alloc when both solves the same purpose?

Original source