Reputation: 1770
i want update the text of my label every time i receive notification from nsmanageObjContext.
this is my code for add the observer:
- (IBAction)requestFotPhoto {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateLabel) name:NSManagedObjectContextDidSaveNotification
object:self.facebook.managedObjectContext];
and this is the method for update the label:
-(void)updateLabel
{
NSString *text = [NSString stringWithFormat:@"Downalad %i pictures",[Photo NumeberOfAllPhotosFromContext:self.facebook.managedObjectContext]];
dispatch_async(dispatch_get_main_queue(), ^{
//UIKIT method
NSLog(@"text %@",text);
[self.downlaodLabel setText:text];
});
}
i assume that updateLabel is execute in a another thread, so i execute the instructions for update the label on the main thread, but this code has no effect. where is the problem?
obviously the NSlog print the right message!
thanks!
Upvotes: 1
Views: 473
Reputation: 14328
seems like:
NSNotificationCenter addObserver
code, from your (IBAction)requestFotPhoto
(seems is some button click event handler
, which only run after user tapped) to viewDidLoad
shold like this:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabel) name:NSManagedObjectContextDidSaveNotification object:self.facebook.managedObjectContext];
}
dispatch_async
should like this:
- (void)updateLabel:(NSNotification *) notification {
NSLog (@"updateLabel: notification=%@", notification);
if ([[notification name] isEqualToString: NSManagedObjectContextDidSaveNotification]) {
NSDictionary *passedInUserInfo = notification.userInfo;
NSString *yourText = [passedInUserInfo objectForKey:@"dataKey"];
//UIKIT method
NSLog(@"yourText=%@",yourText);
[self.downlaodLabel setText:yourText];
}
}
NSString *newText = @"someNewText";
NSDictionary *passedInfo = @{@"dataKey": newText};
[[NSNotificationCenter defaultCenter] postNotificationName:NSManagedObjectContextDidSaveNotification object: self userInfo:passedInfo];
for more detail pls refer another post answer
Upvotes: 0
Reputation: 410
In your situation you don't need to use dispatch_async
, because notification handlers are run in the main thread. They are executed in a main loop on idle moments — sorry if I'm wrong with techincal words, english is not native for me.
And one more thing: you should't reference self
from blocks, because self
points to your block, and block points to self
— they're not going to be released. If you really want to do it, you can read this question.
Upvotes: 0