1. 程式人生 > >iOS之UIViewController執行返回操作並傳遞引數值的兩種方式

iOS之UIViewController執行返回操作並傳遞引數值的兩種方式

舉個例子,第一個page(即UIViewController)顯示天氣,需要對所在地進行設定,這就需要跳轉到第二個page,選擇好所在地之後,將所在地資訊(即返回引數)傳回第一個page。

第一種:通過Delegate的Protocol

1.新建PassValueDelegate.h

Cpp程式碼  收藏程式碼
  1. #import <Foundation/Foundation.h>  
  2. @protocol PassValueDelegate <NSObject>  
  3. -(void)passValue:(NSString *)value;  
  4. @end  

 2.在需要得到返回值的UIViewController.h新增對PassValueDelegate的實現

Cpp程式碼  收藏程式碼
  1. @interface IkrboyViewController6 : UIViewController<PassValueDelegate>  

 3.在UIViewController.m實現-(void)passValue的方法,即處理得到的返回值的事件

Cpp程式碼  收藏程式碼
  1. -(void)passValue:(NSString *)value{  
  2.     NSLog(@"get backcall value=%@",value);  
  3. }  

 4.在下一個UIViewController.h(即為上一個UIViewController提供返回資料)新增Delegate的引數

Cpp程式碼  收藏程式碼
  1. @property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;  

 5.在上一個UIViewController跳轉到下一個UIViewController之前新增程式碼

Cpp程式碼  收藏程式碼
  1. //設定第二個視窗中的delegate為第一個視窗的self  
  2.     newViewController.delegate = self;  

 6.下一個UIViewController返回到上一個UIViewController的程式碼

Cpp程式碼  收藏程式碼
  1. self dismissViewControllerAnimated:YES completion:^{  
  2.             //通過委託協議傳值  
  3.             [self.delegate passValue:@"ululong"];  
  4.     }];  

第二種:繫結Notification,利用userInfo引數

 1.在第一個UIViewController的viewDidLoad添加註冊RegisterCompletionNotification程式碼

Cpp程式碼  收藏程式碼
  1. [[NSNotificationCenter defaultCenter] addObserver:self  
  2.                                              selector:@selector(registerCompletion:)  
  3.                                                  name:@"RegisterCompletionNotification"  
  4.                                                object:nil];  

 2.別忘了解除·Notification

Cpp程式碼  收藏程式碼
  1. - (void)didReceiveMemoryWarning  
  2. {  
  3.     [super didReceiveMemoryWarning];  
  4.     // Dispose of any resources that can be recreated.  
  5.     [[NSNotificationCenter defaultCenter] removeObserver:self];  
  6. }  

3.實現registCompletion方法

Cpp程式碼  收藏程式碼
  1. -(void)registerCompletion:(NSNotification*)notification {  
  2.     //接受notification的userInfo,可以把引數存進此變數  
  3.     NSDictionary *theData = [notification userInfo];  
  4.     NSString *username = [theData objectForKey:@"username"];  
  5.     NSLog(@"username = %@",username);  
  6. }  

 4.在下一個UIViewController的返回操作中新增程式碼

Cpp程式碼  收藏程式碼
  1. NSDictionary *dataDict = [NSDictionary dictionaryWithObject:@"MissA"  
  2.                                                          forKey:@"username"];  
  3.     [[NSNotificationCenter defaultCenter]  
  4.      postNotificationName:@"RegisterCompletionNotification"  
  5.      object:nil  
  6.      userInfo:dataDict];  
  7.     [self dismissViewControllerAnimated:YES completion:nil];