我保留、使用然后释放的警报视图对象上的 EXC_BAD_ACCESS
我知道这是一个常见问题,所以我需要一个解释,这样我就不会再遇到这个问题了。在我的头文件中,我定义了一个 UIAlertView 并保留它,如下所示:
@interface myController {
UIAlertView *alert;
}
@property (nonatomic, retain) UIAlertView *alert;
在我的实现中,我按如下方式使用和重用此警报:
@synthesize alert;
...
if (self.alert != nil) {
[self.alert release];
}
self.alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: @"Ok To Send", nil];
[self.alert show];
我还在我的 dealloc 中释放了它。
所以,我听说过内存管理的黄金法则,但我显然不理解它。黄金法则规定,您绝不能释放未通过 alloc 保留或获取的对象。您必须始终最终释放您保留的或通过 alloc 获得的对象。
我将它保留在头文件中,所以我最终必须在 dealloc 中释放它。在我的实现中,我多次执行警报对象的分配,因此每次我准备重新分配它时,我都会释放旧的。
请帮助我理解我的误解。
I know this is a common problem, so I need an explanation so I don't keep having this problem. In my header file, I have defined a UIAlertView and retained it as shown:
@interface myController {
UIAlertView *alert;
}
@property (nonatomic, retain) UIAlertView *alert;
In my implementation, I use and reuse this alert as follows:
@synthesize alert;
...
if (self.alert != nil) {
[self.alert release];
}
self.alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: @"Ok To Send", nil];
[self.alert show];
I also release this in my dealloc.
So, I've heard the golden rule on memory management, but I apparently don't understand it. The golden rule says that you must never release an object that you have not either retained or obtained via alloc. You must always eventually release an object that you have either retained or obtained via alloc.
I retained it in the header file, so I eventually must release it in the dealloc. In my implementation, I perform an alloc of the alert object more than once, so each time I get ready to re-alloc it, I release the old one.
Please help me understand what I am misunderstanding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
指定了
retain
的@property
是这样实现的...因此,通过为属性分配一个新值,该属性将处理
release
之前的值...所以当您手动释放
它时,您就过度释放了。此外,由于您已将
@property
设置为retain
,因此您应该在分配给该属性之前autorelease
:The
@property
withretain
specified is implemented something like this...So by assigning a new value to the property, the property will handle the
release
of the previous value... so when you manuallyrelease
it, you're over-releasing.Also, since you have the
@property
set toretain
, you shouldautorelease
before assigning to the property:您的财产保留。因此,当您设置 self.* 时,它会为您保留。类似地,当您将属性设置为 nil 或另一个对象时,它会释放旧的属性对象。
Your property retains. So when you set with self.* it retains for you. Similarly when you set the property to nil or another object it release the old property object.
看来你双重保持了警惕!
self.alert 执行保留,您的对象已经保留计数为 1,因为它是用 alloc init 实例化的
试试这个:
相反!
Looks like you are double-retaining your alert!
self.alert does a retain, your object has already retainCount of 1 since it's been instantiated with alloc init
Try this:
instead!