在 iPhone SDK 中处理此问题的典型方法是定义委托协议。例如:
@protocol SecondViewControllerDelegate
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text;
@end
然后你会添加一个delegate 属性到你的SecondViewController,比如:
//in the .h file
@interface SecondViewController : UIViewController {
//declare instance variables
}
@property(nonatomic, assign) id<SecondViewControllerDelegate> delegate;
@end
//in the .m file
@implementation SecondViewController
@synthesize delegate;
//[code...]
@end
然后您将更新 FirstViewController 以实现委托协议:
//in the .h file
@interface FirstViewController : UIViewController<SecondViewControllerDelegate> {
//[instance variables]
}
//[methods and properties]
@end
//in the .m file
@implementation FirstViewController
//[code...]
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text {
//do whatever you need to do with the text
}
//[code...]
@end
...并在FirstViewController 创建SecondViewController 时设置委托字段:
SecondViewController* sv = [[SecondViewController alloc] init];
sv.somestring = someanotherstring;
sv.delegate = self;
最后,在SecondViewController 中实现viewWillDisappear 大致如下:
- (void) viewWillDisappear: (bool)animated {
[super viewWillDisappear:animated];
if (self.delegate) {
[self.delegate viewControllerWillDisappearWithLabelText: myLabel.text];
}
}