使用 Objective-C 中的块传递数据

Passing data using blocks in Objective-C

我有两个视图控制器,分别是 ViewControllerA 和 ViewControllerB。

ViewcontrollerB 上有表格视图单元格。单击表格视图单元格时,我想将 ViewControllerB 上选择的数据发送到 ViewControllerA 上的标签。

我知道可以通过多种方式实现,但是如何通过blocks.Kindly建议实现。

提前致谢!

ViewController B

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *viewArr = [self.array objectAtIndex:indexPath.row];

    NSLog(@"the value obtained on cell is %@",viewArr);
    ViewController *vc=[[ViewController alloc]init];
    vc.aSimpleBlock(viewArr);   
}

我不知道这是否明智甚至可能。

为了在视图控制器之间直接传递数据,我经常使用委托。我会向 B 添加一个委托 属性 并让它定义一个委托协议。我会让 A 实现该协议并让 B 调用这些协议方法来传递数据。当然,将 B 的委托设置为 A。

在那种情况下,您必须提供来自 ViewControllerA 的块,以便另一个 (ViewControllerB) 可以处理它(作为 属性),保留它并当您 select 第 table 行时调用。

但是委托的好处呢?事实上,委派更像是一种在这种情况下使用的标准模式。

在你的ViewController一个

1) 为块 say typedef void (^simpleBlock)(NSString*);

声明一个 typedef

2) 创建一个像

这样的块变量
@property(nonatomic,strong)simpleBlock  aSimpleBlock;

3) 在viewDidAppear / viewDidLoad

中定义这个块
aSimpleBlock = ^(NSString* str){
        NSLog(@"Str is the string passed on tableView Cell Click..!!");
    };

在你的 ViewController B 你有 tableView 的地方

1)-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

只需将您的 block 称为

your_VC_A_Object.aSimpleBlock("Your_Label_String_here");

你可以在viewControllerB中定义一个block并设置它 ViewController A,当select一个cell时,你可以调用这个block并给它传值,比如:
在viewControllerB中

// ViewControllerB.h
@interface ViewControllerB : UITableViewController

@property (nonatomic, copy) void (^didSelectCellBlock)(id obj);
@end

// ViewControllerB.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *str = [self.dataArray objectAtIndex:indexPath.row];
        if (self.didSelectCellBlock) {
            self.didSelectCellBlock(str);
        }
        ...
    }
}

在ViewController一个

 ViewControllerB *controllerB = [[ViewControllerB alloc] init];
 __weak __typeof(self) weakSelf = self;
 controllerB.didSelectCellBlock = ^(id obj) {
     weakSelf.label.text = (NSString *)obj;
 };

第 1 步

最初将 VC-B 的父 class 添加到 VC-A

@interface ViewControllerA : ViewControllerB

第 2 步

ViewControllerB

上创建接口中的一个常用方法
@interface ViewControllerB : UIViewController

-(void)shareContent:(NSString*)currentText;

第 3 步

在那个 ViewControllerB 实现文件上

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
     __weak typeof(self) weakSelf = self;

      dispatch_async(dispatch_get_main_queue(), ^ {

         [weakSelf shareContent: [_items objectAtIndex:indexPath.row]];

    });


}

第四步

在您的 ViewControllerA 实现文件上

 -(void)shareContent:(NSString*)currentText
 {

   NSLog(@"Local details:%@", currentText);
 }

选择-2

for alternate Way , you can get the sample from here or example