开发者

Silly memory management issue that has me stumped

开发者 https://www.devze.com 2023-02-24 06:06 出处:网络
I have a property defined as: @property(nonatomic, retain) UITableView *settingsTableView; Then in my viewDidLoad method I have:

I have a property defined as:

@property(nonatomic, retain) UITableView *settingsTableView;

Then in my viewDidLoad method I have:

self.settingsTableView = [[[UITableView alloc] initWithFrame:tableFrame style:UITableViewStyleGrouped] autorelease];
[self.view addSubview:self.settingsTableView];
[self.settingsTableView release];

Then in the dealloc method of the view controller I have:

[settingsTableView release];

When I attempt to do the release from within the dealloc I am getting a "message sent to deallocated instance". I am starting to second guess myself, anybody see anything stupid in what I've done?

Really appreciate the help on thi开发者_如何学运维s one!


you're calling release on an object you've already autoreleased. Just get rid of the line

[self.settingsTableView release];

and you should be good.

Note that you should keep the release in the dealloc method, since the property calls retain for you, but not release.


Two things. First, you're over-releasing the table view in the first place: the autorelease call negates the need for a manual release afterwards.

Also, in general, what you release in -dealloc are things that you created in -init, -initWithCoder:, or whatever, not loadView or -viewDidLoad. In this case, the method you're looking for is -viewDidUnload; you just have to set self.settingsTableView to nil in that method, and the property setter will handle releasing it if necessary.


Here is the change you need to make.

self.settingsTableView = [[[UITableView alloc] initWithFrame:tableFrame style:UITableViewStyleGrouped] autorelease];
[self.view addSubview:self.settingsTableView];
[self.settingsTableView release];
//^^^ This line is bad no need to release this value until dealloc
//if it is defined as retain or copy


Seems obvious. You have already released with

[self.settingsTableView release];

So why release it again in the dealloc?


I believe the problem is related to your use of autorelease when you are allocating and initializing the UITableView.

You also might have a problem with releasing the settingsTableView right after you use it, vs. in the dealloc method. Anytime you alloc/init an object, you should only release it once.

If you use autorelease, the rules are a little different, so I'd recommend reading up on that again. Also, when you pass objects that you've created off to other things, they may take complete or shared ownership of the object by retaining it, meaning that you may or may not need to release it yourself anymore. The documentation for that should be on the method you're calling (like addSubView).

0

精彩评论

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

关注公众号