开发者

Correct memory management pattern for alloc/initing a view, adding to subview and returning

开发者 https://www.devze.com 2023-03-05 06:10 出处:网络
Im sure this sort of question has been asked to death and I understand what I should be doing, but its not working. My app is crashing:

Im sure this sort of question has been asked to death and I understand what I should be doing, but its not working. My app is crashing:

Here's the code:

    PDFViewController *cv = [[PDFViewController alloc] initWithNibName:@"PDFViewController" bundle:[NSBundle mainBundle]];
cv.view.frame = CGRectMake(0, 0, 1024, 748);

    [self.view addSubview:cv.view];

Now, if I send a release message to the cv instance:

      [cv release];

My application crashes. Same if I add it to the autorelease pool (on a开发者_开发问答lloc/init). Now my concern is this:

0) I'm alloc/init'ing, so its my duty to release (or add to auto-release pool).

1) Calling addSubview:cv.view increments the retain count of the cv.

2) I should be able to send it a release message, because it's being retained by the self.view.

3) What's wrong?

TIA.

EDIT Solution

PDFViewController *cv = [[PDFViewController alloc] initWithNibName:@"PDFViewController" bundle:[NSBundle mainBundle]];
[self presentModalViewController:cv animated:YES];


Calling addSubview:cv.view does not increments the retain count of the cv object. It does increments the retained count on "cv.view" therefore "self.view" only retains "cv.view".


cv.view is a getter that automatically has the view ivar calling autorelease. Your best bet is probably to create an ivar _cv and use that instead of a local variable. Then safely release the ivar in your dealloc: [_cv release]; _cv = nil;

0

精彩评论

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