3

所以我有一个基本的应用程序,这是它的工作原理。我有一个名为 A 的根视图控制器和一个名为 B 的表视图控制器。当用户在 BI 中选择一行时,会弹出回到根视图控制器 A。

而我想要做的是将被选为 NSString 的行的数据传递回根视图控制器 A。然后根据字符串使用此字符串“做某事”。

我曾尝试使用 NSNotification 方法,但后来我无法使用该字符串做某事。

这是我尝试过的:

//tableViewB.m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData" object:[[_objects objectAtIndex:indexPath.row] objectForKey:@"title"]];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//rootViewA.m
-(void)dataReceived:(NSNotification *)noti
{
     NSLog(@"dataReceived :%@", noti.object);

}
-(void)viewDidLoad {
  [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@"passData" object:nil];
}

我想要做的更像是你在推送 viewController 并使用 perpareForSegue 方法时可以做的事情。

在此先感谢您的帮助。

4

3 回答 3

1

您正在做正确的事情,但使用了错误的参数。通知帖子中的object:参数是发送对象。还有另一种 post 方法允许调用者附加userInfo:如下:

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

    // notice the prettier, modern notation
    NSString *string = _objects[indexPath.row][@"title"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData"
                                                        object:self
                                                      userInfo:@{"theString" : string }]
    [self.navigationController popToRootViewControllerAnimated:YES];
}

在接收端,只需使用相同的密钥从通知的用户信息中获取数据:

-(void)dataReceived:(NSNotification *)notification {

     NSLog(@"dataReceived :%@", notification.userInfo[@"theString"]);
}
于 2014-05-28T03:48:58.837 回答
1

使用委托:它会比 NSNotification 更好

表视图.h:

@protocol tableViewDelegate
-(void) tableViewSelectRowWithString:(NSString*)str;
@end

@interface tableView:UITableViewController //or something like this

@property(nonatomic,weak) id<tableViewDelegate> delegate;

表视图.m:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath     {
[self.delegate tableViewSelectRowWithString:@"your string"];
[self.navigationController popToRootViewControllerAnimated:YES];
}

-(void) dealloc{self.delegate = nil;}

//rootViewA.h

@interface rootViewA : UIViewController<tableViewDelegate>

//rootViewA.m

//When create tableView and push view:
tableView *t = ....;
tableView.delegate = self

-(void) tableViewSelectRowWithString:(NSString*)str{//use string}
于 2014-05-28T03:50:29.723 回答
0

试试这个可能会有所帮助

    MyAController *myController = (MyAController *)[self.navigationController.viewControllers objectAtIndex:0];
    myController.myText = @"My String" ;
    [self.navigationController popToViewController:myController animated:YES];

我已经使用了很多次.. 它工作正常.. 注意:替换你的类名和字符串。谢谢 :)

于 2014-05-28T04:34:49.743 回答