Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alloc, init, and new in Objective-C [duplicate]

Tags:

objective-c

One book for about iPhone programming instantiates classes like this:

[[Class alloc] init] 

Another book about Objective-C does it like this:

[Class new] 

What's the difference?

like image 926
neuromancer Avatar asked Jul 25 '10 20:07

neuromancer


People also ask

What is Alloc and init in Objective-C?

Alloc allocates memory for the instance, and init gives it's instance variables it's initial values. Both return pointers to the new instance, hence the method chain.

What does Alloc mean in Objective-C?

In its simplest form: alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable. init: short for initialization, sets up the object and returns the object.

What is the difference between Foo new and [[ Foo alloc init?

One Short Answere is: Both are same. But. 'new' only works with the basic 'init' initializer, and will not work with other initializers (eg initWithString:).

What is new in Objective-C?

A new type has been added to Objective-C, aptly named instancetype. This can only be used as a return type from an Objective-C method and is used as a hint to the compiler that the return type of the method will be an instance of the class to which the method belongs.


1 Answers

+new is implemented quite literally as:

+ (id) new {     return [[self alloc] init]; } 

Nothing more, nothing less. Classes might override it, but that is highly atypical in favor of doing something like +fooWithBar:.

like image 88
bbum Avatar answered Sep 25 '22 05:09

bbum