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

视图1.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方法访问吗?

最佳答案

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

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

10-07 19:44
查看更多