在通知后在主线程上执行选择器时显示加载叠加层

时间:2013-02-14 08:30:58

标签: iphone objective-c selector nsnotificationcenter

我正在开发一个iPhone应用程序。

我正在从服务器进行异步更新。更新完成下载后,我发出NSNotification

[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DATA_RECEIVED object:self userInfo:@{ @"updateKey": updateKey }];

在我的viewController中,我声明了观察者

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateReceived:) name:NOTIFICATION_DATA_RECEIVED object:nil];

收到通知时将执行的选择器:

- (void) updateReceived:(NSNotification *)notification
{
    [self performSelectorOnMainThread:@selector(updateData:) withObject:nil waitUntilDone:NO];
}

updateData需要在主线程上执行,因为它会更改核心数据中的实体,除非我们使用某些特定的库,否则无法在不同的威胁上执行。我不想改变它。

我的问题:

updateData需要一段时间,因为它位于主线程上,所以它正在冻结UI。我需要在完成此操作后显示“正在加载数据...”叠加。

我在视图控制器中有2个方法可以显示叠加层:showLoadingOverlayhideLoadingOverlay

我需要在调用showLoadingOverlay时调用updateData,并在完成后调用hideLoadingOverlay

问题是,由于它在主线程上执行,我不知道如何在更新数据时显示叠加层。我尝试在发送通知之前直接显示它并在updateData方法的末尾隐藏它但它不起作用。

非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:0)

也许,只是也许,你正在使用也在主线程上安排但在执行updateData之后的动画。在这种情况下,请尝试确保在调用updateData之前启动动画。例如,您可以执行以下操作:

- (void)updateReceived:(NSNotification*)notification {
    [self startAnimationOnComplete: ^{
        [self performSelectorOnMainThread:@selector(updateData:) withObject:nil waitUntilDone:NO];
    }]
} 

答案 1 :(得分:0)

我找到了办法。 我最终使用NSTimer在显示叠加层1毫秒后运行updateReceived方法。

- (void) updateReceived:(NSNotification *)notification
{
    [self showLoadingOverlay];
    [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(updateDataOnMainThread:) userInfo:nil repeats:NO];
}

- (void) updateDataOnMainThread:(NSTimer *)timer
{
    [self performSelectorOnMainThread:@selector(updateData:) withObject:nil waitUntilDone:NO];
}