2011-10-21 47 views
0

我知道这是一个常见问题,所以我需要一个解释,所以我不会有这个问题。在我的头文件,我已经定义了一个UIAlertView中,并保留它,如:EXC_BAD_ACCESS对警告视图对象我保留,使用,然后释放

@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中释放它。在我的实现中,我不止一次地执行了一个警告对象的分配,所以每当我准备好重新分配它时,我就释放旧的。

请帮我理解我的误解。

回答

1

@property与指定实现这样的事情retain ...

-(void)setAlert:(UIAlertView*)alert 
{ 
     if (self->alert != alert) 
     { 
       [self->alert release]; 
       self->alert = [alert retain]; 
     } 
} 

因此,通过对财产分配一个新的值,该属性将处理前值的release ......所以,当你手动release它,你过度释放。

而且,由于你有@property设置为retain,你应该autorelease分配给属性之前:

self.alert = [[[UIAlertView alloc] initWithTitle:title 
             message:message 
             delegate:self cancelButtonTitle:@"Cancel" 
           otherButtonTitles: @"Ok To Send", nil] autorelease]; 

[self.alert show]; 
+0

真棒。非常感谢你的解释。我一遍又一遍地被它困扰着 – JeffB6688

1

你的财产保留。所以当你用自己设定的时候*它会保留给你。同样,当您将该属性设置为零或另一个对象时,它会释放旧的属性对象。

1

看起来你是双重保留你的警报! self.alert做了保留,你的对象已经1 retainCount,因为它被实例化的alloc初始化

试试这个:

//if (self.alert != nil) { 
// [self.alert release]; 
//} 

self.alert = nil; 

alert = [[UIAlertView alloc] initWithTitle:title 
            message:message 
            delegate:self 
cancelButtonTitle:@"Cancel" otherButtonTitles: @"Ok To Send", nil]; 

[self.alert show]; 

,而不是!

+1

我个人认为这是在你不需要的属性“经典”案例(除非你需要访问另一个类的警报......) – ortnec

+0

或者是alertView委托,公平地说,我不认为他是因为我看不到任何协议列出。 – NJones

相关问题