簡體   English   中英

內存訪問錯誤:有關發行版,協議和委托的問題

[英]Memory bad acces: Questions with releases, protocols and delegates

我對內存管理有一個小疑問是iOS ...

好吧,我定義了一個擁有一個協議的視圖。 在另一個類中,我創建另一個類的實例,將視圖添加到其他視圖,然后嘗試釋放實例。 由於收到BAD_ACCS錯誤,因此在調用協議的方法時出現問題。 它是這樣的:

- (void)viewDidLoad{
    Class1 *c1 = [[Class1 alloc]init];
    [c1 setDelegate:self];
    [self.view addSubview:c1.view];
    [c1 release];
}

- (void)methodOfProtocolClass1 {
    NSLog(@"c1 method called")
}

Class1有一個按鈕,當我按下它時,我調用methodOfProtoclClass1並出錯。 有人知道如何釋放該對象嗎?

謝謝,

大衛

您在這里過度釋放c1 ...

- (void)viewDidLoad{
    Class1 *c1 = [[Class1 alloc]init]; //allocates Class1 instance with +1 ref count

    [c1 setDelegate:self];
    [self.view addSubview:c1.view];
    [c1 release]; //releases c1, ref count goes to 0 and the memory is reclaimed later
}

因此,您獲得了錯誤的訪問權限,您的c1實例不見了,並且在viewDidLoad方法結束時無效

您不必釋放c1,而必須保留它! addSubview不保留c1實例,它僅保留其視圖! 如果以后再參考c1,將會獲得錯誤的訪問權限

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM