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?
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.
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.
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:).
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.
+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:
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With