开发者

allocating object again

I have a following code:

[chart removeFromSuperview];
[chart rele开发者_运维问答ase];
chart = nil;
BNPieChart *aChart = [[BNPieChart alloc] initWithFrame:self.view.frame];
self.chart = aChart;
[aChart release];

And as I want, chart is deallocating, but in variable is still something, next when I want to assign aChart to chart I've got EXC_BAD_ACCESS. So I decided to assign nil to chart.

Is this a good practice?


Even better, replace:

[chart release];
chart = nil;

With:

self.chart = nil;

 

You get BAD_ACCESS because when you assign a retained/copied property with dot syntax it gets auto-released. Therefore it will work correctly even like this:

[chart removeFromSuperview];
BNPieChart *aChart = [[BNPieChart alloc] initWithFrame:self.view.frame];
self.chart = aChart;

self.chart = aChart will do the release for you.


HI badeleux ...i think not because you get error or crash EXE_BAD_ACCESS . that you are attempting to accessing something that you already release .


If you already have chart set as a retained property, rather than using

[chart release];
chart = nil;

You can just write;

self.chart = nil;

You can do this because the automatic code resulting from your @synthesize chart will do the release for you. Many regard this as better practice as it will ensure messages aren't accidentally sent to non-nil objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜