我正在嘗試製作一個簡單的iphone應用程序,我一直在玩功能和最近,代表。我只是對內存管理感到困惑,因爲顯然「很好的代碼」讓我的應用程序崩潰exc_bad_access。objective-c內存管理澄清
我有一個對象有兩個數據成員,現在實現爲空。
@implementation semester: NSObject{
NSInteger ID;
NSString *name;
}
然後我的委託方法:
- (void) receiveSemester:(semester *)newSemester {
[test setText:newSemester.name];
}
並且被用作具有這樣的形式的圖:
@interface addSemesterController : UIViewController {
id<ModalViewDelegate> delegate;
UITextField *txtName;
UILabel *prompt;
UIButton *ok;
UIButton *cancel;
}
所有對象是由屬性和應用程序中的文件合成。下面是使用的委託方法:
- (IBAction) okClick:(id)sender{
// create semester object and return it
semester *created = [[semester alloc] init];
created.name = txtName.text;
[delegate receiveSemester:created];
[self dismissModalViewControllerAnimated:YES];
}
我的dealloc方法是這樣的:
- (void)dealloc {
/*
[txtName dealloc];
[prompt dealloc];
[ok dealloc];
[cancel dealloc];
*/
[super dealloc];
}
與包含在表格中的對象的deallocs註釋掉,我的應用程序運行正常。然而,當我去掉它們,我收到EXC_BAD_ACCESS錯誤在我的委託協議:
// in main view controller
- (void) receiveSemester:(semester *)newSemester {
[test setText:newSemester.name];
// test is a UILabel
}
我嘗試了殭屍的方法和它說,標籤調用一個釋放的對象。我不會在「form」控制器中釋放我的學期對象,即使我是在取消分配視圖之前調用委託函數。
顯然我不應該在dealloc方法中釋放對象,我只是不清楚爲什麼我不應該。
再次,在此先感謝您的幫助。
使用[txtName release]; [及時發佈]; [確定發佈]; [取消發佈];而不是dealloc,你也可以使用ARC自動引用計數.....與ARC你不需要使用dealloc,release,它會自動釋放內存....並且你在開始時選擇它,當你創建一個新的項目,您還可以通過編輯在ARC中更改您的項目。 – TheTiger
對不起,我找不到ARC選項,它在哪裏? – gamda
當你創建一個新的項目 - 並在你給你的項目名稱的窗口..見下面有一個選項 - 「使用自動引用計數」只是選中此框...然後按下.. – TheTiger