分配/初始化视图、添加到子视图和返回的正确内存管理模式
我确信这种问题已经被问到死了,我明白我应该做什么,但它不起作用。我的应用程序崩溃了:
这是代码:
PDFViewController *cv = [[PDFViewController alloc] initWithNibName:@"PDFViewController" bundle:[NSBundle mainBundle]];
cv.view.frame = CGRectMake(0, 0, 1024, 748);
[self.view addSubview:cv.view];
现在,如果我向 cv 实例发送发布消息:
[cv release];
我的应用程序崩溃了。如果我将其添加到自动释放池(在 alloc/init 上),则相同。 现在我关心的是:
0)我正在分配/初始化,所以我有责任释放(或添加到自动释放池)。
1) 调用 addSubview:cv.view 会增加 cv 的保留计数。
2)我应该能够向它发送一条发布消息,因为它被保留 自我看法。
3)怎么了?
TIA。
编辑 解决方案
PDFViewController *cv = [[PDFViewController alloc] initWithNibName:@"PDFViewController" bundle:[NSBundle mainBundle]];
[self presentModalViewController:cv animated:YES];
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 alloc/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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用 addSubview:cv.view 不会增加 cv 对象的保留计数。它确实增加了“cv.view”上的保留计数,因此“self.view”仅保留“cv.view”。
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
是一个 getter,它会自动让视图 ivar 调用 autorelease。您最好的选择可能是创建一个 ivar_cv
并使用它而不是局部变量。然后在你的 dealloc 中安全地释放 ivar:[_cv release]; _cv = nil;
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;