使用块将数据传回给视图控制器

我正在看这个问题 。

其中一个答案显示了如何使用块向后传递数据查看prepareForSegue方法。 我的理解是,这个方法应该被用来向前传递数据,而不是向后传递。

我想为此尝试阻塞 – 将数据传递回另一个viewController。

我的问题是:如何做到这一点,而不使用prepareForSegue方法? 我可以在例如UITableView – didselectRowAtIndexPath并closures视图 – 但接收视图如何得到“通知”有数据回来,而不使用委托?

向后发送数据

  1. 在你的secondViewController.h文件中声明block

    @property (nonatomic, copy)void(^myBlock)(NSString *);

  2. 调用块,无论您需要从secondViewController .m文件传递数据

    myBlock(@"this will displayed in firstViewController");

3.导入上面的.h文件在你的firstViewController .m文件中,并定义你的block

 secondViewController *ref =[[secondViewController alloc ]init]; ref.myBlock =^void(NSString *data) { self.labelOffirstviewcontroller=data; }; 

在你的视图控制器1中:

 MyViewControllerClass2* vc2 = [[MyViewControllerClass2 alloc] initWithNibName:@"UIViewController" bundle:[NSBundle mainBundle] completion:^{ NSLog(@"view2 is closed"); }]]; [self.navigationController pushViewController:vc2 animated:YES]; 

在MyViewControllerClass2.m中:

 @interface MarryViewController () @property (nonatomic, copy) void(^completion)(); @end @implementation MarryViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completion:(void(^)())completion { self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if( self ) { //store completion block _completion = completion; } return self; } -(void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; //call completion block _completion(); } 

在MyViewControllerClass2.h中:

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completion:(void(^)())completion; 

只是关于如何真棒块几个笔记:

  1. MyViewControllerClass2不知道在_completion()中定义了什么,这是主要的,因为这不是他所关心的

  2. 你也可以在-dealloc中调用_completion(),甚至在MyViewControllerClass2将继续运行的地方

  3. 你可以传递参数来阻塞函数

  4. 你可以传递块函数的参数

  5. 还有很多 :)

我真的很鼓励人们对块和统计使用他们很好的概述,因为他们很酷。

重要!

在使用块的时候不要声明委托,委托方法和使用块的主要思想和抽象结果是一样的。 此外,委托模式具有logging效果更好,使用更加严格等优点。 仍然块更灵活,并且(当习惯时)更容易使用。

问候,

hris.to

我知道你特别要求一个不涉及prepareForSegue的解决scheme,但是这似乎是基于prepareForSegue仅用于传递数据的假设。

有一种叫做“放松”的东西,可能会对你的情况有所帮助。 这里有详细的讨论。

如果您特别想为此使用块,则可以简单地将块属性添加到您的子控制器,并让父控制器设置该块。 子控制器在被解雇时将不得不调用该块。 如果你这样做,要小心保留循环。 对我来说,听起来不像块是在这种情况下最好的解决scheme,但很难说没有更多上下文的权威。

是的方法可以向前或向后发送数据,以便您可以使用BlocksDelegates有关ios中的块的更多信息,请使用此链接CLICK HERE

希望它能帮助你,thnx