Search code examples
objective-cpopoverdelegationnsnotification

Refreshing a view from a popover


I am using Xcode 4.5 and targeting iOS 5 and above.
I have a popover that allows a user to change the background of the underlying view.

When tapping on the "button", it requires that I tap twice to see the change.
I am using NSNotification. I have tried Delegation, yet it does nothing.
Any help or tips would be greatly appreciated.

From viewWillAppear:

    // nav button is for background image selection
    navigationBtn.tag = buttonTag;
    [navigationBtn setBackgroundImage:[UIImage imageNamed:tempImage] forState:UIControlStateNormal];

    if (selectFlag) {
       [navigationBtn addTarget:self action:@selector(BGSelected:) forControlEvents:UIControlEventTouchUpInside];
    } else {
       navigationBtn.adjustsImageWhenHighlighted = NO;
    }

And the method for selection:

- (void)BGSelected:(id)sender { 
    self.bgtag = [sender tag];
    SettingsDAO *settingsDao = [[SettingsDAO alloc] init];

    if ([self.currentView isEqualToString:@"New_Journal"])
    {
       NSLog(@"Update Journals Background");
       [settingsDao updateJournalBackgroundId:self.journalId withBackgroundId:self.bgtag];
    }
    // notification to let EntryView know the background has changed
    [[NSNotificationCenter defaultCenter] postNotificationName:@"aBackgroundChanged"
                                                    object:self];

    [settingsDao release];
}

the NSNotification Method:

- (void)aBackgroundChanged:(NSNotification *)notification {
    [self invalidate];
    [self reloadSettings];
}

Solution

  • If you are using storyboard, and your popover is a segue you can do like that:

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
       // perform all the operations...ecc
       [[(UIStoryboardPopoverSegue*)segue popoverController] setDelegate:self];
    }
    

    Then you have to make sure your caller controller has all the delegate methods.

    Or, with NSNotification:

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
       // perform all the operations...ecc
       [[NSNotificationCenter defaultCenter]
           addObserver:self
           selector:@selector(changeBackground:)
           name:BackgroundHasChangedNotification
           object:[segue destinationViewController]];
    }
    

    Then just remember to remove observer in dealloc, and in change background method:

    -(void)changeBackground:(NSNotification*)notification {
    
       NSDictionary *userInfo = notification.userInfo;
       // I assume you are using background name
       NSString *backgroundName = [userInfo objectForKey:BackgroundOneConstant];
       // do the rest....
    
    }