2014-02-25 27 views
0

1)我通過使用自定義 協議的兩個視圖控制器之間傳遞值。但該值始終顯示NULL。使用自定義協議在兩個視圖控制器之間傳遞數據值

我需要從第二視圖控制器值傳遞給第一視圖控制器

2)在Secondview或者Controller.h

@protocol PopoverTableViewControllerDelegate <NSObject> 

@property (nonatomic, strong) id<PopoverTableViewControllerDelegate>myDelegate; 

3)secondview Controller.m或者

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

{ 
     NSDictionary*dict=[sercharray objectAtIndex:index]; 
     str=[dict objectForKey:@"id"]; 
     NSLog(@"test value %@",str); 
     [self.myDelegate didSelectRow:str]; 
     NSLog(@"delegate value %@",self.myDelegate); 
//THIS VALUE ALWAYS SHOWING NULL AND ALSO I SHOULD PASS THIS VALUE TO FIRST VIEW 
     CONTROLLER.I SHOULD USE DISMISS VIEW CONTROLLER. 
     [self dismissViewControllerAnimated:YES completion:nil]; 
    } 

4 )第一視圖controller.h

@interface Firstviewcontroller : 
    UIViewController<PopoverTableViewControllerDelegate> 

5)首先查看Controller.m或者

secondviewcontroller *next=[[seconviewcontroller alloc]init]; 
next.myDelegate=self; 


(void)didSelectRow:(NSString *)cellDataString { 
    passstring = cellDataString; 
    NSLog(@"pass string %@",pass string); 
//first view controller str variable value i need to pass this string[passstring].  
} 
+0

您是否在第二視圖controller.m中獲得了str的值? –

+0

是的,我的第二視圖controller.m –

+0

str得到的價值是您的secondViewController委託方法在解散後在您的FirstViewController類中調用.. –

回答

0

我想你可能是有關用了什麼代表團以及爲什麼有點困惑。例如,如果您在ViewController中執行某種操作並需要通知另一個子類正在執行該操作或該操作的結果,則可能需要在UIViewController子類中創建一個協議。現在爲了讓想要了解動作(接收者)的子類,它必須在它的頭文件中符合該協議。您還必須將代表「設置」給接收班級/控制員。有很多方法可以獲得對接收控制器/類的引用,以將其設置爲委託,但常見的錯誤是分配並初始化該類的新實例,以便在該類已創建時將其設置爲委託。那就是將新創建的類設置爲委託,而不是已經創建並等待消息的類。你想要做的只是給新創建的類傳遞一個值。既然你只是創建這個UIViewController類所需要的只是接收器中的一個Property(ViewControllerTwo)。在你的情況下的NSString:

@Property (nonatiomic, retain) NSString *string; //goes in ViewControllerTwo.h 

,當然也不要在主忘記:

@synthesize string; //Goes in ViewControllerTwo.m 

現在有沒有必要在你的ViewControllerTwo二傳手。

- (void)setString:(NSString *)str //This Method can be erased 
{         //The setter is created for free 
    self.myString = str;   // when you synthesized the property 
} 

當您使用@synthesize時,setter和Getters是免費的。只需將值傳遞給ViewController。除了委託代碼之外,其實現與您的代碼完全相同:

ViewControllerTwo *two = [[ViewControllerTwo alloc] initWithNibName:@"ViewControllerTwo" bundle:nil]; 
[two setString:theString]; 
[self.navigationController pushViewController:two animated:YES]; 
[two release]; 
相關問題