使用自定义协议在两个视图控制器之间传递数据值

时间:2014-02-25 07:03:42

标签: ios iphone objective-c xcode5

1)我使用自定义传递两个视图控制器之间的值     protocol..但该值始终显示为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)First View 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].       
 }

1 个答案:

答案 0 :(得分:0)

我认为您可能会对代表团的用途和原因感到困惑。例如,如果您在该ViewController中执行某种操作并且需要通知另一个子类正在执行该操作,或者该操作的结果,您可能希望在UIViewController子类中创建协议。现在为了想要知道动作(接收器)的子类,它必须在它的头文件中符合该协议。您还必须将委托“设置”到接收类/控制器。有很多方法可以获取对接收控制器/类的引用以将其设置为委托,但是一个常见的错误是分配和初始化该类的新实例以将其设置为委托,此时该类已经创建。这样做是将新创建的类设置为委托,而不是已经创建并等待消息的类。您尝试做的只是将值传递给新创建的类。因为你刚刚创建了这个UIViewController类所需的所有东西都是接收器中的一个Property(ViewControllerTwo)。在你的情况下是一个NSString:

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

当然不要忘记在主要内容:

@synthesize string; //Goes in ViewControllerTwo.m

现在,ViewControllerTwo中不需要setter。

- (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];
相关问题