2012-03-01 63 views
0

我剛剛開始學習Objective C/Cocoa,我知道內存管理是多麼重要,我相信這個錯誤是我一直在關注的。編程接收信號:EXC_BAD_ACCESS。該怎麼做?

我有一個非常非常簡單的屏幕:兩個UITextView,一個按鈕,一個UILabel。

我的頭文件有:

@interface PontaiViewController : UIViewController { 

UITextField *loginField; 
UITextField *passwordField; 
UILabel *userID; 

} 

@property (nonatomic, retain) IBOutlet UITextField *loginField; 
@property (nonatomic, retain) IBOutlet UITextField *passwordField; 
@property (nonatomic, retain) IBOutlet UILabel *userID; 


- (IBAction) btnLoginClicked:(id) sender; 

實施有:

@implementation PontaiViewController 
@synthesize loginField; 
@synthesize passwordField; 
@synthesize userID; 
-(IBAction) btnLoginClicked:(id)sender { 
NSString *string1 = @"username="; 
NSString *string2 = [string1 stringByAppendingString:(loginField.text)]; 
NSString *string3 = [string2 stringByAppendingString:(@"&password=")]; 
NSString *post = [string3 stringByAppendingString:(passwordField.text)]; 
NSLog(@"The post is %@", post); 
userID.text=loginField.text; 
[string1 release]; 
[string2 release]; 
[string3 release]; 
[post release]; 

}

,並與

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
    self.loginField=nil; 
    self.passwordField=nil; 
    self.userID=nil; 
} 

- (void) dealloc { 
    [super dealloc]; 
    [loginField release]; 
    [passwordField release]; 
    [userID release]; 
} 

完成當我運行這個演示,並嘗試寫som在TextView中,我得到這個錯誤。

它可能是什麼?

的問候,費利佩

+0

錯誤發生在哪裏?在'userID.text = loginField.text;'?如果是這樣,你確定你將'userID'字段連接到了Interface Builder中的某些東西嗎? – 2012-03-01 22:17:58

回答

2

viewDidUnload設置loginFieldnil,然後嘗試釋放它在dealloc。這是不對的。您只需要發佈您擁有的有效商品。

此外,(如評論中指出的),您需要將[super dealloc]放在dealloc函數的末尾。

正如其他人所指出的,你也不應該釋放你從stringByAppendingString得到的字符串。

下面是關於如何在Objective-C的iOS下的內存管理的一些基本規則:

你會發現https://developer.apple.com/library/ios/#documentation/general/conceptual/devpedia-cocoacore/MemoryManagement.html

的一件事是,你只能釋放的東西,你有責任,你是除非你用的這些之一創建概不負責:

頁頭,allocWithZone:,副本,copyWithZone:,mutableCopy,mutableCopyWithZone

+0

我看到 我以爲我對我用'retain'keywoard創建的對象負責。 感謝您的提示! – 2012-03-02 14:36:46

+0

當然! Obj-C中的內存管理與普通的C/C++有很大不同,而且一開始學習起來可能會非常棘手。 – Almo 2012-03-02 14:50:04

3

而且,你的NSString的是自動釋放,然後」再次釋放它們(釋放)。閱讀有關便捷方法的內存管理。

+0

另請嘗試:'NSString * post = [NSString stringWithFormattedString:@「username =%@&password =%@」,loginField.text,passwordField.text];'不要用這個例子發佈帖子。 – dbrajkovic 2012-03-01 22:25:24

+1

另外'[super dealloc];'應該最後一次。 – dbrajkovic 2012-03-01 22:26:50

+0

謝謝!欣賞它 – 2012-03-02 14:37:11

2

stringByAppendingString返回一個自動釋放的對象,不釋放string1string2string3post

1

你應該註釋掉,因爲你使用的輔助方法,而不是明確分配任何以下

//[string1 release]; 
//[string2 release]; 
//[string3 release]; 
//[post release]; 

相關問題