1

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

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

数据库已更新,uploadSession 返回新的详细信息,并且预订会相应更新。所有这一切都很好地响应 - 在不到一秒钟的时间内,始终如一地启动和返回。

当我尝试使用从预订对象更新(在 uploadSession 完成块内)BookingViewController读取的值来更新 UI(交货日期和价格的标签)时,就会出现问题。

BookingViewController 被分配为预订的代表。预订是在其自己的“价格”属性上为 KVO 设置的。每当价格发生变化时,预订就会调用priceDidChange:(NSString *)updatedPriceon的委托方法BookingViewController,从而触发对and的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.textpriceLabel.text 的更新非常缓慢- 延迟大约在 5 到 12 秒之间变化。

NSLogs到处都是,并且相信这不仅仅是延迟从预订对象获取更新值。很容易我已经看到了二十次“ priceDidUpdate delegate notification-updatedPrice is: 0.00”(更新后的价格),然后算到 10 之前self.priceLabel.text实际上设置为@"0.00". 完全被难住了。

万一它很重要,它NSURLSession被配置为使用ephemeralSessionConfiguration没有调整。

根据调用是来自uploadTask完成块内部还是外部,是否有任何理由导致UI更新BookingViewController需要更长的时间?priceDidChange

提前致谢!

4

1 回答 1

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];
    });
}
于 2015-06-09T13:19:41.170 回答