2012-03-01 40 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]; 

相关问题