iOS:在视图之间传递数据

时间:2012-02-03 08:57:48

标签: objective-c ios nsnotificationcenter

我有两个以编程方式创建的视图。我们将它们命名为view1和view2。在view1中有一个选择器和一个按钮。这个想法是当用户选择值并按下按钮选择值以便从view2访问时。为此,我使用NSNotificationCenter。这是一些代码。

view1.m

-(void)registerNotification
{
    NSDictionary *dict = [NSDictionary dictionaryWithObject:self.selectedOption forKey:@"data"];

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"pickerdata" 
     object:self
     userInfo:dict];
}

-(void)loadSecondView
{
    self.secondView = [[secondViewController alloc]init];
    [self.view addSubview:self.secondView.view];
    [self registerNotification];
    [self.secondView release];
}

view2.m

-(id)init
{
   if(self = [super init])
   {
    [[NSNotificationCenter defaultCenter] 
         addObserver:self 
         selector:@selector(reciveNotification:) 
         name:@"pickerdata" object:nil];
   }
   return self;
}


-(void)reciveNotification:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"pickerdata"])
    {
        NSLog(@"%@", [NSString stringWithFormat:@"%@", [[notification userInfo] objectForKey:@"data"]]); // The output of NSLog print selected value

       // Here is assignment to ivar
        self.selectedValue = [NSString stringWithFormat:@"%@", [[notification userInfo] objectForKey:@"data"]];
    }
}

问题从这里开始。对该值感兴趣的逻辑在loadView方法中实现。问题是loadView在reciveNotification方法和selectedValue尚未包含所需信息之前执行。 怎么做从NSNotificationCenter提供的信息可以从loadView方法访问?

1 个答案:

答案 0 :(得分:2)

我不知道我是否完全理解你的问题,但将值直接传递给viewController而不是处理通知会不会更容易?

-(void)loadSecondView
{
    self.secondView = [[secondViewController alloc]init];
    self.secondView.selectedValue = self.selectedOption;
    [self.view addSubview:self.secondView.view];
    [self.secondView release];
}