star_kid
star_kid

Reputation: 191

Purpose of using alloc in objective C

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?

Upvotes: 3

Views: 164

Answers (2)

lindinax
lindinax

Reputation: 282

Graham Lee already gave the correct answer that's why you should accept it as the correct one. Nowadays, in my opinion [NSNumber numberWithInt:42]; is just a short cut of [[NSNumber alloc] initWithInt:42]

Upvotes: 2

user23743
user23743

Reputation:

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

Upvotes: 12

Related Questions