NSArray arrayWithObjects reference counts


when we build the array to attach to the tab bar controller we did:

[code]UIViewController *vc1 = [[HypnosisViewController alloc] init];
UIViewController *vc2 = [[CurrentTimeViewController alloc] init];
NSArray *viewControllers = [NSArray arrayWithObjects: vc1, vc2, nil];

[vc1 release];
[vc2 release];

If we did that all inline would we have a memory leak because we wouldn’t have a reference to send release to?

NSArray *viewControllers = [NSArray arrayWithObjects: [[HypnosisViewController alloc] init], [[CurrentTimeViewController alloc] init], nil];



Take HypnosisViewController for example. By allocating it, it has a retain count of 1. By adding it to an array, it has a retain count of 2. At some point in the future, the array (which has the only reference to the HypnosisViewController) is destroyed, and it releases its hold on the HypnosisViewController, decrementing the retain count to 1. No other object has a reference to the HypnosisViewController, but it still exists because it has a retain count of 1. Classic memory leak.

Keep in mind, you could do this:

NSArray *viewControllers = [NSArray arrayWithObjects:
                        [[[HypnosisViewController alloc] init] autorelease],
                        [[[CurrentTimeViewController alloc] init] autorelease],

That would be okay.


Thanks Joe - it’s all making sense now.