开发者

Calling release method crashes iOS app

I have subclassed UIView as a Toolbar and add all kinds of buttons and other views to the class. Now, in my ViewController header I have this:

@interface GridViewController : UIViewController <UIWebViewDelegate, UIScrollViewDelegate> {
    Toolbar *toolbar;
}

@property (retain) Toolbar *toolbar;

and in the implementation I have this:

@synthesize toolbar;

- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect toolbarRect = CGRectMake(0, 0, 1024, 40);
    self.toolbar = [[Toolbar alloc] initWithFrame:toolbarRect];
    [self.view addSubview:toolbar];
}

- (void) dealloc {
    [toolbar release];
    [super dealloc];
}
开发者_开发知识库

Now, if I run analyze, it basically says that I have a potential memory leak. If I add [toolbar release]; right after calling addSubView:toolbar like I do usually when adding subviews the app crashes when I pop the ViewController.

What am I doing wrong? I’ve tried reading all about the memory management and according to that you always have to release/autorelease the things you alloc/copy/retain etc. If I look at my code, I’m retaining the instance variable in the header and also allocating it in the implementation, so the retain count should be +2 and thus I’d need to release it twice, but it seems I have misunderstood something. Any help is very much appreciated.

When I say crash, I get this: Xcode pauses and says that EXC_BAD_ACCESS for this line in main.m

int retVal = UIApplicationMain(argc, argv, nil, nil);

and in console I get this:

modifying layer that is being finalized - 0x60895f0 


If the property self.toolbar is set to (retain) it suggests that after the line self.toolbar = [[Toolbar alloc] initWithFrame: toolbarRect]; the retain count should be +2. I'd suggest replacing that line with self.toolbar = [[[Toolbar alloc] initWithFrame: toolbarRect] autorelease] to make the retain count remain at 1. That should probably fix it, as the retain that comes from addSubview is not managed by you and you release toolbar in the dealloc.

All properties with retain setters should be given an autoreleased object.


It seems that the problem was actually in the Toolbar class and not the ViewController. I wasn’t using setters for the ivars and thus it started breaking.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜