Clark
Clark

Reputation: 406

How To Refresh a View Using NSNotification without [view setNeedsDisplay];

I have two classes, one UIViewController and one UITableViewCell, called MoodViewController and TableViewCell respectively.

The MoodViewController has an image view, which I would like to refresh every time a UISwitch state changes. I am posting a notification on the switch state change, and the notification is being received. However, I can't figure out what code to use within the Notification handler that will allow me to refresh the image view automatically. I have tried [myImageViewName setNeedsDisplay]; however, I cannot seem to get a view to refresh after the Notification is received.

The code that I am currently using to handle the notification is as follows:

-(void)handleNotification:(NSNotification *)notification {

NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if ([[standardDefaults stringForKey:@"switchKey"] isEqual: @"On"]) {

    self.aReference.moodLabel.text = @"Happy";
    self.aReference.moodImage.image = [UIImage imageNamed: _array1[0]];
    [self.aReference.moodImage setNeedsDisplay];
}
else {

    self.aReference.moodImage.image = nil;
    [self.aReference.moodImage setNeedsDisplay];

}
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Note: I am trying to refresh the image view which is NOT part of the table, so please don't suggest [tableViewName reloadData]; unless I am missing something.

Any help would be greatly appreciated -- Thanks!

Upvotes: 0

Views: 162

Answers (3)

Bamsworld
Bamsworld

Reputation: 5680

Could it be that you're removing the observer on first call to the handler?

Try removing the line -

[[NSNotificationCenter defaultCenter] removeObserver:self];

This line will remove self from all notifications that self is observing.

Upvotes: 0

user1858341
user1858341

Reputation: 1

Maybe the notification is being sent to another thread? You could make sure that the UI changes are done in the main thread.

Upvotes: 0

sergio
sergio

Reputation: 69027

Your code should work.

One possible explanation for it not working is that self.aReference.moodImage (or self.aReference) is nil when the notification handler is executed. Please, check this.

Upvotes: 1

Related Questions