开发者

C array in Objective-C maintains pointer to object already deallocated

From the code:

Thing *thingA = [[Thing alloc]init];
// thingA pointer reference 0x00998

Thing *things[] = {thingA};

[thingA release];
// release method of the Thing class correctly invoked

thingA = nil;
// thingA pointer reference now is 0x0

NSLog(@"%d", things[0]);
// odd, because things[0] 开发者_StackOverflow中文版still maintains the pointer reference 0x00998

Why does the element things[0] maintain the pointer reference 0x00998? In the moment that thingA goes dealloc through release and after to set to nil (the reference to thingA now is 0x0) how things[0] still the reference to 0x0998? I thought that things[0] pointer would look with 0x0.


Line thingA = nil; affects only thingA reference. It doesn't affect any other reference or object itself.

You can make this example a bit simpler

Thing *thingA = [[Thing alloc]init];
Thing *thingB = thingA;

[thingA release];
thingA = nil;

// thingA is nil, but thingB still has old reference

Note, that since object itself is released, you shouldn't use thingB reference: memory it points to may be used for something else already.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜