2014-12-13 23 views
0

我有以下代碼,並且一直在掙扎它很長一段時間。我有兩個視圖控制器,FirstView和SecondView。我從FirstView pushViewController到SecondView。在SecondView中有一個UITextView,用於輸入用戶的輸入。然後,我使用SecondView中的委託將該輸入保存到FirstView的變量(稱爲文本)中。當我運行它時,代碼從SecondView調用委託進入無限循環。與視圖控制器運行到無限循環代理

FirstView.m

UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
SecondView *secondView = [story instantiateViewControllerWithIdentifier:@"SecondView"]; 
secondView.delegate = self; 
[self.navigationController pushViewController:secondView animated:YES]; 

-(void)setText:(NSString *)strData 
{ 
NSLog(@"Entered setText delegate"); 
NSLog(@"Current string is %@", strData); 
self.text = strData; 
} 

SecondView.h

@protocol SetInstructionDelegate <NSObject> 
-(void)setText:(NSString *)strData; 
@end 

@property (weak, nonatomic) IBOutlet UITextView *textView; 
@property (nonatomic, weak) id<SetInstructionDelegate> delegate; 

SecondView.m

-(void)viewDidLoad { 
/****************************** Done Button framing ********************************/ 
UIButton *btn_bar=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 60)]; 
[btn_bar setBackgroundColor:[UIColor clearColor]]; 
[btn_bar setTitle:@"Done" forState:UIControlStateNormal]; 
[btn_bar addTarget:self action:@selector(doneEditing:) forControlEvents:UIControlEventTouchUpInside]; 
UIBarButtonItem *doneEdit=[[UIBarButtonItem alloc]initWithCustomView:btn_bar]; 
self.navigationItem.rightBarButtonItem=doneEdit; 
} 

-(void)doneEditing:(id) sender 
{ 
[self.view.window endEditing: YES]; 
[self.navigationController popViewControllerAnimated:YES]; 
NSLog(@"Current text is : %@", self.textView.text); 
[[self delegate] setText:self.textView.text]; 
} 

代碼停留在doneEditing,並保持反覆印刷NSLogs。我閱讀了很多關於這方面的鏈接,但找不到明確的答案並一直在掙扎。我對iOS和委託方法非常陌生。任何幫助,將不勝感激。謝謝!

+0

使用調試器。你可以清楚地看到遞歸如何發生,如果你停下來看看。 – matt 2014-12-13 01:08:23

回答

0

問題是你有一個名爲text的屬性和一個名爲setText:的方法。給那個方法(或那個屬性,我不在乎哪個)一個不同的名字。真的應該是方法;大肆提供一種以set...開頭的名字永遠是一件非常危險的事情。

原因是設置名爲text的屬性實際上不過是調用名爲setText:的方法的簡寫。因此,這是一個無限循環:

-(void)setText:(NSString *)strData 
{ 
self.text = strData; 
} 

該代碼,你看,是正是等於說:

-(void)setText:(NSString *)strData 
{ 
[self setText: strData]; 
} 

看,你的無限遞歸在其所有的榮耀。

+0

非常感謝@Matt。是的,我會在將來確定二傳手方法。這真的很有用。 – 2014-12-13 01:15:38

+0

這是使用Swift代替Objective-C的另一個好理由。在Swift中,這個陷阱並不存在。那就是_why_ Swift的設計方式就是這樣;其目的是幫助防止人們陷入典型的Objective-C隱藏陷阱。 – matt 2014-12-13 01:18:04

+0

如果我的答案是解決問題,請考慮接受它(複選標記)。 – matt 2014-12-13 02:19:07