UI缓慢更新*仅*如果响应NSURLSessionUploadTask完成块中发生的更改而调用

时间:2015-06-09 12:57:45

标签: ios objective-c delegates nsurlsession nsurlsessionuploadtask

应用程序与我服务器上的php脚本交互。用户可以创建预订,并将详细信息写入数据库。随后,他们可以取消预订。

在应用程序中,预订是一个对象,负责从服务器收集自己的详细信息。预订也可以取消(根据用户的要求) - 按下"取消按钮"在BookingViewController中调用预订的(void)cancelBooking方法,该方法使用带有bookings-cancel.php的json数据的NSURLSessionUploadTask发布到@{ @"invoiceNumber": self.invoiceNumber }

数据库已更新,uploadSession将返回新的详细信息,并且预订会根据更新自行进行更新。所有这一切都很好地响应 - 在不到一秒的时间内,一直保持响应。

当我尝试使用之后的预订对象中读取的值更新BookingViewController上的用户界面(交付日期和价格的标签)时出现问题已更新(在uploadSession完成块内)。

BookingViewController被指定为预订代表。预订是为KVO设置的,价格为#34;属性。只要价格发生变化,预订就会在priceDidChange:(NSString *)updatedPrice上调用代理方法BookingViewController,触发NSLog并更新为deliveryLabel.textpriceLabel.text

- (void)priceDidUpdate:(NSString *)updatedPrice {
    NSLog(@"priceDidUpdate delegate notification - updatedPrice is: %@", updatedPrice);
    [self.deliveryLabel setText:@"N/A"];
    [self.priceLabel setText:updatedPrice];
}

测试显示,如果我直接从"取消"更新价格按钮,或者在uploadTask 之外的cancelBooking方法中的任何其他显式命令(例如,self.price = @" 123.45"),然后UI更新就像写出NSLog一样快(即接近瞬间)。

但是,如果价格在uploadTask完成块中更新,NSLog将以响应的方式写出,但deliveryLabel.text和priceLabel.text的更新速度非常慢发生 - 延迟大约在5到12秒之间变化。

我到处都有NSLogs,我相信这不仅仅是延迟了预订对象的更新价值。很容易二十次我见过" priceDidUpdate delegate notification - updatedPrice是:0.00" (更新后的价格),然后在self.priceLabel.text实际设置为@"0.00"之前计入10。完全难倒。

如果重要,NSURLSession使用ephemeralSessionConfiguration配置,无需调整。

根据BookingViewController的调用是否来自uploadTask完成块的内部或外部,priceDidChange中的UI更新是否需要更长的时间?

提前致谢!

1 个答案:

答案 0 :(得分:3)

使用主队列更新UI。使用以下代码:

- (void)priceDidUpdate:(NSString *)updatedPrice 
{
    dispatch_async(dispatch_get_main_queue(), ^()
    {
            //Add method, task you want perform on mainQueue
            //Control UIView, IBOutlet all here
            NSLog(@"priceDidUpdate delegate notification - updatedPrice is: %@", updatedPrice);
            [self.deliveryLabel setText:@"N/A"];
            [self.priceLabel setText:updatedPrice];
    });
}