1

每次收到来自 nsmanageObjContext 的通知时,我都想更新标签的文本。

这是我添加观察者的代码:

- (IBAction)requestFotPhoto {

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(updateLabel) name:NSManagedObjectContextDidSaveNotification
                                           object:self.facebook.managedObjectContext];

这是更新标签的方法:

-(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];
        });
}

我假设 updateLabel 在另一个线程中执行,所以我在主线程上执行更新标签的指令,但是这段代码没有效果。问题出在哪里?

显然 NSlog 打印了正确的信息!

谢谢!

4

2 回答 2

0

在您的情况下,您不需要使用dispatch_async,因为通知处理程序在主线程中运行。它们在空闲时刻在主循环中执行 - 抱歉,如果我对技术词汇有误,英语对我来说不是母语。

还有一件事:你不应该self从块中引用,因为self指向你的块,而块指向self——它们不会被释放。如果你真的想这样做,你可以阅读这个问题

于 2013-10-06T18:23:04.027 回答
0

看起来像:

  • 您应该将您的NSNotificationCenter addObserver代码从您的(IBAction)requestFotPhoto(似乎是一些button click event handler,仅在用户点击后运行)移动到viewDidLoad

保持这样:

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabel) name:NSManagedObjectContextDidSaveNotification object:self.facebook.managedObjectContext];
}
  • 对于通知处理程序,不使用dispatch_async

应该是这样的:

- (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];

有关更多详细信息,请参阅另一个帖子答案

于 2021-11-02T09:37:41.043 回答