ios - 当我使用委托(delegate)将值传递给另一个 ViewController 时,我发现委托(delegate)什么都不做

标签 ios objective-c cocoa-touch delegates

当我使用委托(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/

相关文章:

objective-c - 在 Mac OSX 上监控鼠标状态

ios - 如何自定义分组表格 View 单元格的背景/边框颜色?

ios - UIGestureRecognizer 无法识别

ios - 必须触摸 fbloginview 两次才能工作

ios - 如何链接 iOS 的静态库

objective-c - 将短 Zulu 格式日期转换为 NSDate

ios - SwiftUI 关闭多个模态表

ios - 管理推送通知横幅文本

ios - UITextView 三边边框

iphone - 是否可以同时使用 UIPanGesture 和 UISwipeGesture?