Init vs other methods



I have seen in the book 2 different ways to initialize an array :

NSArray *array = [NSArray array];

(or NSArray *array = [NSArray arrayWithObjects:obj1, obj2, obj3, nil]:wink:


NSArray *array = [[NSArray alloc]init];

Am I correct by saying that :

  • both are possible,
  • when it is possible, use the most precise method (array)
  • [[xxx alloc]init] is a more general way to initialize an object, that is usable almost for every case

Does that make sense ?



Before ARC there was a difference between


(Trivia: a2 was autoreleased, a1 was not.)

But, with ARC the two are exactly the same.

Now, because init is defined in NSObject and other methods are not, you are always safe doing

Poodle *p = [[Poodle alloc] init];


Thank you very much for your answer, Aaron
That makes things very clear.




Just want to ask a question within this thread as it saves space.

So with the above example - if I were to create an instance of my object like this:

NSDate *date = [NSDate date] NSLog (@ "Today's date: %@", date);

And this way:

[code] NSDate *date = [[NSDate alloc]init];
[date timeIntervalSinceNow];

NSLog(@"Today:%@", date); 


Both give the same results.

From my understanding the former initialises my date object with the current date - all in own line. The second option is more β€œclear” of what is happening - but does the same thing in two lines?