你需要使用委托协议...以下是如何做到这一点:
在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的头文件中,通过以下操作订阅Second Delegate协议:
#import "SecondViewController.h"
@interface FirstViewController:UIViewController <SecondDelegate>
现在,当您在FirstViewController中实例化SecondViewController时,您应该执行以下操作:
// If you're using a view controller built with Interface Builder.
SecondViewController *second = [[SecondViewController alloc] initWithNibName:"SecondViewController" bundle:[NSBundle mainBundle]];
// If you're using a view controller built programmatically.
SecondViewController *second = [SecondViewController new]; // Convenience initializer that uses alloc] init]
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; //And there you have it.....
}
现在,当您要取消第二个视图控制器时,您希望调用在第一个视图控制器中实现的方法.这部分很简单.您所要做的就是在第二个视图控制器中,在解除代码之前添加一些代码:
if([self.myDelegate respondsToSelector:@selector(secondViewControllerDismissed:)])
{
[self.myDelegate secondViewControllerDismissed:@"THIS IS THE STRING TO SEND!!!"];
}
[self dismissModalViewControllerAnimated:YES];
委托协议非常、非常、非常有用.熟悉一下它们会对你有好处:)
NSNotification是实现此目的的另一种方式,但作为最佳实践,当我希望跨多个viewController或对象进行通信时,我更喜欢使用它.如果你对使用NSNotitification感兴趣,这是我在早些时候发布的一个答案:Firing events accross multiple viewcontrollers from a thread in the appdelegate
编辑:
如果要传递多个参数,则解除之前的代码如下所示:
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内的Second Delegate方法实现现在将如下所示:
- (void) secondViewControllerDismissed:(NSString*)stringForFirst argument2:(NSObject*)inObject1 argument3:(NSObject*)inObject2
{
NSString thisIsTheDesiredString = stringForFirst;
NSObject desiredObject1 = inObject1;
//....and so on
}