当我使用委托(delegate)将值传递给另一个 ViewController
时,我发现委托(delegate)什么都不做。
我可以删除委托(delegate),但我仍然可以传递值!
当我需要将值从 ViewControllerA
传递到 ViewControllerB
时,我只是这样做了!
- (IBAction)sendToB:(id)sender {
ViewControllerB *viewB=[[ViewControllerB alloc]initWithNibName:@"ViewControllerB" bundle:nil];
[viewB getValue:self.textInput.text];
[self presentViewController:viewB animated:YES completion:nil]; }
然后在 ViewControllerB
中,我确实得到了值。
但这与委托(delegate)无关,我记得人们都说使用委托(delegate)在两个 ViewControllers
之间传递值。那有什么区别呢?谢谢!
最佳答案
您可以通过多种方式传递值,您展示的一种也用于传递值。
但假设发生这种情况,您必须将值从您提供的 ViewControllerB
更新到 ViewControllerA
那么我相信您不会初始化 ViewControllerA
然后尝试传递值。
在这种情况下,您将需要 delegate
来执行此操作,您可以通过以下方式使用 protocol
来实现:-
在 ViewControllerB.h
文件中创建您的协议(protocol)
@protocol sampleDelegate <NSObject>
- (void)updatedValue:(NSString* )newData;
@end
@property (nonatomic,assign)id<delegate>delegateObj;
在ViewControllerB.m
文件中
- (IBAction)sendToA:(id)sender
{
[self.delegateObj updatedValue:@"Updated value"];
}
现在在 ViewControllerA.m
文件中覆盖您的 ViewControllerB
委托(delegate)对象:
- (IBAction)sendToB:(id)sender
{
ViewControllerB *viewB=[[ViewControllerB alloc]initWithNibName:@"ViewControllerB" bundle:nil];
[viewB setDelegate:self];
[viewB getValue:self.textInput.text];
[self presentViewController:viewB animated:YES completion:nil];
}
//Implement the protocol method here in ViewControllerA.m
- (void)updatedValue:(NSString* )newData
{
NSLog(@"Value that updated in ViewControllerB is %@",newData);
}
希望这可以帮助您了解委托(delegate)的重要性。 :)
关于ios - 当我使用委托(delegate)将值传递给另一个 ViewController 时,我发现委托(delegate)什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032187/