轉自:
http://blog.csdn.net/heng615975867/article/details/39005699
舉個例子,第一個page(即UIViewController)顯示天氣,需要對所在地進行設置,這就需要跳轉到第二個page,選擇好所在地之後,將所在地信息(即返回參數)傳回第一個page。
第一種:通過Delegate的Protocol
1.新建PassValueDelegate.h
- #import <Foundation/Foundation.h>
- @protocol PassValueDelegate <NSObject>
- -(void)passValue:(NSString *)value;
- @end
2.在需要得到返回值的UIViewController.h添加對PassValueDelegate的實現
- @interface IkrboyViewController6 : UIViewController<PassValueDelegate>
3.在UIViewController.m實現-(void)passValue的方法,即處理得到的返回值的事件
- -(void)passValue:(NSString *)value{
- NSLog(@"get backcall value=%@",value);
- }
4.在下一個UIViewController.h(即爲上一個UIViewController提供返回數據)添加Delegate的參數
- @property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;
5.在上一個UIViewController跳轉到下一個UIViewController之前添加代碼
- //設置第二個窗口中的delegate爲第一個窗口的self
- newViewController.delegate = self;
6.下一個UIViewController返回到上一個UIViewController的代碼
- self dismissViewControllerAnimated:YES completion:^{
- //通過委託協議傳值
- [self.delegate passValue:@"ululong"];
- }];
第二種:綁定Notification,利用userInfo參數
1.在第一個UIViewController的viewDidLoad添加註冊RegisterCompletionNotification代碼
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(registerCompletion:)
- name:@"RegisterCompletionNotification"
- object:nil];
2.別忘了解除·Notification
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
3.實現registCompletion方法
- -(void)registerCompletion:(NSNotification*)notification {
- //接受notification的userInfo,可以把參數存進此變量
- NSDictionary *theData = [notification userInfo];
- NSString *username = [theData objectForKey:@"username"];
- NSLog(@"username = %@",username);
- }
4.在下一個UIViewController的返回操作中添加代碼
- NSDictionary *dataDict = [NSDictionary dictionaryWithObject:@"MissA"
- forKey:@"username"];
- [[NSNotificationCenter defaultCenter]
- postNotificationName:@"RegisterCompletionNotification"
- object:nil
- userInfo:dataDict];
- [self dismissViewControllerAnimated:YES completion:nil];