Init vs other methods


#1

Hello,

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:

and

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 ?

Thanks
Fred


#2

Before ARC there was a difference between

and

(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];


#3

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

Fred


#4

Hi

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); 

[/code]

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?