您需要使用委托协议...以下是操作方法:
在您的secondViewController的头文件中声明一个协议。它看起来应该像这样:
#import <UIKit/UIKit.h>
@protocol SecondDelegate <NSObject>
-(void)secondViewControllerDismissed:(NSString *)stringForFirst
@end
@interface SecondViewController : UIViewController
{
id myDelegate;
}
@property (nonatomic, assign) id<SecondDelegate> myDelegate;
不要忘记在实现(SecondViewController.m)文件中合成myDelegate:
@synthesize myDelegate;
在您的FirstViewController的头文件中,通过执行以下操作订阅SecondDelegate协议:
#import "SecondViewController.h"
@interface FirstViewController:UIViewController <SecondDelegate>
现在,当您在FirstViewController中实例化SecondViewController时,应该执行以下操作:
SecondViewController *second = [[SecondViewController alloc] initWithNibName:"SecondViewController" bundle:[NSBundle mainBundle]];
SecondViewController *second = [SecondViewController new];
second.myString = @"This text is passed from firstViewController!";
second.myDelegate = self;
second.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:second animated:YES];
[second release];
最后,在您的第一个视图控制器的实现文件(FirstViewController.m)中,为secondViewControllerDismissed实现SecondDelegate的方法:
- (void)secondViewControllerDismissed:(NSString *)stringForFirst
{
NSString *thisIsTheDesiredString = stringForFirst;
}
现在,当您要关闭第二个视图控制器时,您要调用第一个视图控制器中实现的方法。这部分很简单。您要做的就是在第二个视图控制器中,在关闭代码之前添加一些代码:
if([self.myDelegate respondsToSelector:@selector(secondViewControllerDismissed:)])
{
[self.myDelegate secondViewControllerDismissed:@"THIS IS THE STRING TO SEND!!!"];
}
[self dismissModalViewControllerAnimated:YES];
委托协议非常有用,非常有用。熟悉它们对您有好处:)
NSNotifications是执行此操作的另一种方法,但是作为最佳实践,当我想在多个viewController或对象之间进行通信时,我更喜欢使用它。如果您对使用NSNotifications感到好奇,这是我早些时候发布的答案:从appdelegate中的线程在多个viewcontroller中触发事件
编辑:
如果要传递多个参数,则关闭前的代码如下所示:
if([self.myDelegate respondsToSelector:@selector(secondViewControllerDismissed:argument2:argument3:)])
{
[self.myDelegate secondViewControllerDismissed:@"THIS IS THE STRING TO SEND!!!" argument2:someObject argument3:anotherObject];
}
[self dismissModalViewControllerAnimated:YES];
这意味着firstViewController内部的SecondDelegate方法实现现在看起来像:
- (void) secondViewControllerDismissed:(NSString*)stringForFirst argument2:(NSObject*)inObject1 argument3:(NSObject*)inObject2
{
NSString thisIsTheDesiredString = stringForFirst;
NSObject desiredObject1 = inObject1;
}