2014-02-25 24 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]; 
相关问题