NSArray creation P108


#1

Hi all,
When making the array containing the view controllers why do:

NSArray *viewControllers = [NSArray arrayWithObjects: vc1, vc2, nil];

Instead of:

NSArray *viewControllers = [[NSArray alloc] init];
[viewControllers addObject: vc1];
[viewControllers addObject: vc2];

Can anyone explain the benefits of one over the other?
Thanks.


#2

Well, the real benefit is that the second chunk of code is invalid - you can only add objects to a mutable array. But, I don’t think that is what you were asking. :slight_smile:

The first chunk of code is faster - you don’t have to dynamically resize the array for each object and you don’t have to send a message (which has a cost) for each object you plan on adding. Also, the first chunk of code is much more succinct in terms of readability.


#3

Thanks for posting the rationale Joe…this is a very good book and appreciate your responsiveness in answering readers!


#4

Hi Joe,

Is this necessary to release viewControllers after setting view controllers for tabBarController

[tabBarController setViewControllers:viewControllers];
[viewControllers release];   <--- ???

Thanks for your time.


#5

In the scope of this application, no, not really. The NSArray pointed to by viewControllers will exist the entire time the application is running.

However, in general, yes, if you create an object in a method and use a local variable to point to it, you should release it before you leave the method.


#6

Thanks for clearing that up (so quickly).

Awesome book by the way. I really enjoy reading it.


#7

[quote=“JoeConway”]In the scope of this application, no, not really. The NSArray pointed to by viewControllers will exist the entire time the application is running.

However, in general, yes, if you create an object in a method and use a local variable to point to it, you should release it before you leave the method.[/quote]
In this particular example though, you still wouldn’t need to explicitly release viewControllers before leaving the method (even if it didn’t exist the entire time the application was running), since it was created using a convenience method, right? It should be marked for autorelease if I’m understanding correctly.


#8

Right, in the first option where you use arrayWithObjects:, you couldn’t release it, you don’t own it.

It is only in the second one where you are an owner and should release it.