通过segue传递NSNumber

时间:2015-01-21 13:36:36

标签: ios objective-c iphone

我已成功使用prepareForSegue,但我已设法传递变量。我现在试图通过segue的反向传递NSNumber,但prepareForSegue没有被调用。要回到我之前使用的VC:

[self.navigationController popViewControllerAnimated:YES];

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{    
    if ([[segue identifier] isEqualToString:@"ShowImages"]) {
       DiaryViewController  *photoNumber = [segue destinationViewController];
       photoNumber.deleteObject = self.rowTodelete;   
}

我是否可以添加一些内容以使prepareForSegue反向运行。或者我是否需要以某种方式从不同的班级访问我的NSNumber

3 个答案:

答案 0 :(得分:1)

如果您设置了展开segue,则可以获得导致展开的UIViewController

查看此答案here about Unwind Segues

一旦你真正设置了展开segue结构,这里有一些示例展开segue代码:

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue {
    UIViewController* sourceViewController = unwindSegue.sourceViewController;
    if ([sourceViewController isKindOfClass:[DiaryViewController class]] {
    DiaryViewController *photoNumber = (DiaryViewController *)sourceViewController;
    NSNumber *deleteObject = photoNumber.deleteObject;
    }
}

答案 1 :(得分:0)

您也可以使用Delegate-Pattern。 只需将当前Controller设置为目标控制器的Delegate,并创建一个协议,定义委托应该实现的方法。 然后,如果目标控制器被解除,您可以将所需的任何参数传递回源Viewcontroller。

// Source Controller (which is also the delegate of the destination-controller)
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
      SomeController * a = segue.destinationController;
      a.delegate = self;
}
// Delegate Method 
-(void)viewControllerGotDismissed:(NSNumber*)test{
      NSlog(@"TEST:%@",test);
}

// Destination Controller
@protocol SomeProtocol
   -(void)viewControllerGotDismissed:(NSNumber*)test;
@end

// Destination Controller
-(void)viewWillDisappear {
   // ....
  [self.delegate viewControllerGotDismissed:@1337]; // Pass the value to the source Controller
}
@end

答案 2 :(得分:0)

另一种可能适合您的方法是在解除显示的视图时指定一个完成块来运行。例如,如果 A 使用segue显示 B ,则在最初转换为 B 时设置完成块。当 B 即将被解雇时,请运行完成块。

在ViewControllerB.h中

@property (nonatomic, strong) void (^onDismiss)(UIViewController *sender, NSNumber *aNumber);

在ViewControllerB.m

// execute the block right before A is presented again
- (void)viewWillDisappear:(BOOL)animated {
    self.onDismiss(self, aNumberToPassBack);  // Run the block 
}

在ViewControllerA.h中

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"SegueToB"]) {
        ViewControllerB *vcb = [segue destinationViewController];

        vcb.onDismiss = ^(UIViewController *sender, NSNumber *aNumber) {
            self.aNumber = aNumber;
            // ... update your views if needed
        };   
    }
}