简体   繁体   中英

iOS: Passing data between views

I have two views which are created programmatically. Let's name them view1 and view2. In view1 there is a picker and a button. The idea is when the user choose value and press the button selected value to be accessable from view2. For this I use NSNotificationCenter. Here is some code.

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"]];
    }
}

The problem starts here. The logic which is interested of that value is implemented in loadView method. The problems is that loadView is executed before reciveNotification method and selectedValue does not contain needed information yet. What to do so the information provided from NSNotificationCenter to be accessible from loadView method ?

I don't know if I fully understand your question, but wouldn't it be easier to pass the value directly to the viewController instead of dealing with notifications?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM