我有以下代碼,並且一直在掙扎它很長一段時間。我有兩個視圖控制器,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和委託方法非常陌生。任何幫助,將不勝感激。謝謝!
使用調試器。你可以清楚地看到遞歸如何發生,如果你停下來看看。 – matt 2014-12-13 01:08:23