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

时间:2017-02-22 06:29:39

标签: ios objective-c uitableview objective-c-blocks

我有两个viewcontrollers,分别是ViewControllerA和ViewControllerB。

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

我知道它可以通过多种方式实现,但如何通过块来实现。建议。

提前致谢!

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);   
}

5 个答案:

答案 0 :(得分:2)

在ViewController A中

1)声明块的typedef说typedef void (^simpleBlock)(NSString*);

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");

答案 1 :(得分:1)

您可以在viewControllerB中定义一个块并将其设置为ViewController A,当选择一个单元格时,您可以调用此块并将值传递给它,如下所示:
在viewControllerB

npm i

在ViewController A中

// 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);
        }
        ...
    }
}

答案 2 :(得分:1)

<强>步骤-1

最初将VC-B的父类添加到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]];

    });


}

<强>步骤4

在ViewControllerA实现文件上

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

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

选择-2

  

对于备用方式,您可以从hereexample

获取样本

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

那么在这种情况下,您必须提供ViewControllerA的块,以便另一个(ViewControllerB)可以处理它(作为属性),保留它并在您选择表时调用行。

但是对代表团的好处呢?事实上,在这种情况下,委托更像是一种标准模式。

相关问题