我知道這個問題已經在這裏被詢問和回答了很多次。但是我第一次處理這件事,仍然無法在腦海中完美實現它。這裏的代碼我有我實現的代理方法將SecondViewController
的數據傳遞給FirstViewController
。使用委託和協議在2個UIViewController之間傳遞數據
FirstViewController.h
#import "SecondViewController.h"
@interface FirstViewController : UITableViewController<sampleDelegate>
@end
FirstViewController.m
@interface FirstViewController()
// Array in which I want to store the data I get back from SecondViewController.
@property (nonatomic, copy) NSArray *sampleData;
@end
@implementation FirstViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SecondViewController *controller = [[SecondViewController alloc] init];
[self.navigationController pushViewController:controller animated:YES];
}
@end
SecondViewController.h
@protocol sampleDelegate <NSObject>
- (NSArray*)sendDataBackToFirstController;
@end
@interface SecondViewController : UITableViewController
@property (nonatomic, strong) id <sampleDelegate> sampleDelegateObject;
@end
SecondViewController.m
@interface SecondViewController()
@property (strong, nonatomic) NSArray *dataInSecondViewController;
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataInSecondViewController = [NSArray arrayWithObjects:@"Object1", @"Object2", nil];
}
- (NSArray*)sendDataBackToFirstController
{
return self.dataInSecondViewController;
}
@end
我是不是做正確嗎?我希望它將self.dataInSecondViewController
中的數據發送到FirstViewController
,並將其保存在NSArray
屬性sampleData
的FirstViewController
之上。
不知何故,我無法訪問FirstViewController
中的sendDataBackToFirstController
。還有什麼其他的東西想要在那裏訪問sendDataBackToFirstController
?
您需要設置第一個VC爲代表第二個vc。所以第二個vc的委託方法需要在第一個vc中實現。然後在觸發事件時從第二個vc調用該方法。從你的情況來看,如果你想擁有一個數據源或代表,你就不清楚了。如果使用第二個vc作爲第一個vc的數據源,則它是第一個請求數據的vc。但是,當第二個vc發生某種事件時,它只是想返回第一個vc,然後是它的委託類型。然後,您需要將返回類型更改爲void並將數據作爲參數傳遞。 – Anupdas
正確。我試着在我的First vc的didSelectRow中做controller.delegate = self。但不知何故,控制器無法找到委託對象。我的代碼到目前爲止看起來是否正確? –
請按照@gdavis和藝術的答案 – Anupdas