开发者

Help me understand why I don't have to allocate this NSMutableArray

In firstViewController,

SecondViewController *secondViewController = [[[SecondViewController alloc] init] autorelease];
// Pass data to secondViewController
[secondViewController setClass1:anObjectFromFirstViewController];
[[self navigationController] pushViewController:secondViewController ...];

SecondViewController.m

Class1 *class1;
NSMutableArray *object2;

In viewDidLoad, I think object2 points to the same object as class1 and therefore does not need to be allocated.

[self setObject2:[class1 someNSMutableArray]];

In init, I don't have to allocate object2 and the whole app still works. Is it because the object2 is pointing to the same item in memory as [cla开发者_C百科ss1 someNSMutableArray].

If that is the case, then what happens if I do allocate object2. Will there be 2 copies? The app still works the same if I initialize it.

-(id)init { object2 = [[NSMutableArray alloc] init]; }

The confusing part is that if I initialize with autorelease, it will give me a dealloc error, the deallocating to a released object error

-(id)init { object2 = [[[NSMutableArray alloc] init] autorelease]; }

Thanks mucho!!!


Your idea on the first part of the question is correct.

[self setObject2:[class1 someNSMutableArray]];

object2 is a variable which now contains the same address as [class1 someNSMutableArray]. So both point to the same NSMutableArray object.

This is different from:

object2 = [[NSMutableArray alloc] init];

In this case you have created a new NSMutableArray object and put that address in the object2 instance variable. So that is now pointing to a different array than [class1 someNSMutableArray].

The key word there is "created". Think of alloc/init as creating a new object.

As for memory management:

object2 = [[[NSMutableArray alloc] init] autorelease];

I'm assuming you are (correctly) releasing object2 in the -dealloc for this class. So you have two releases (that release in dealloc plus this autorelease here) against only one retain (from the alloc/init), and therefore you are over-releasing the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜