Why NSArray alloc] init] instead of [NSArray array]?


#1

Hello all,

I am curious as to why alloc/init is used when creating objects throughout the book instead of the class method for returning an object?

I have found that using the class methods to create some objects cause the app to crash without any error message returned. For example, when creating an empty array that is an iVar in a custom class. when I go back to alloc/init the application will work, but I am left the extra work of having to dealloc these instances. I thought that was the point of using class methods to create empty array objects, so you didn’t have the responsibility of releasing the array.

I am certain there is a very reasonable explanation…Thanks!!


#2

Remember the retain count rules: if a method doesn’t say alloc, new or copy, the object is autoreleased.

Therefore, when you use a class method, that object will be deallocated as soon as the method exists.

This is why you use alloc/init, because you then own that object and it won’t go away.