UIViewController之間傳遞值的兩種方式

轉自:

http://blog.csdn.net/heng615975867/article/details/39005699


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

第一種:通過Delegate的Protocol

1.新建PassValueDelegate.h

Cpp代碼  收藏代碼
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @protocol PassValueDelegate <NSObject>  
  4.   
  5. -(void)passValue:(NSString *)value;  
  6.   
  7. @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.       
  6.     NSLog(@"username = %@",username);  
  7. }  

 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.   
  8.       
  9.     [self dismissViewControllerAnimated:YES completion:nil];  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章