【问题标题】:NSNotification in Background thread - iOS后台线程中的 NSNotification - iOS
【发布时间】:2017-01-06 07:33:42
【问题描述】:

我正在开发以委托方法接收消息的聊天应用程序。从委托方法中,我调用 NSNotification 来更新 UI 中的消息。

//委托方法

- (void)didReceiveMessage:(XMPPMessage *)message{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"MessageReceived"  object:nil userInfo:@{@"message":message}];
}

我收到的每条新消息都会调用上述委托方法。假设如果我同时收到大量消息,则会导致 UI 挂起。如果我为通知添加后台线程,那么它将为每个委托方法调用创建一个新线程。这不是一个好的解决方案。我该如何处理这种情况?

【问题讨论】:

    标签: ios objective-c multithreading delegates nsnotificationcenter


    【解决方案1】:

    您可以直接向负责更新 UI 的 ViewController 发送消息,而不是在收到消息后发布通知。例如

    - (void)didReceiveMessage:(XMPPMessage *)message{
        MessageListController *messageListController; //get reference as per your UI implementation
        [messageListController updateUIWithMessage:message];
    }
    

    在 updateUIWithMessage 方法中,您可以编写优化代码来更新您的 UI。

    【讨论】:

      【解决方案2】:

      您应该使用NSOperationQueue 并将其设为全局(类级别)。添加NSOperations

      您可以使用maxConcurrentOperationCount 属性来设置最大并发操作数。通过这种方式,您可以同时控制多个操作。但对于你的情况,我认为

      maxConcurrentOperationCount = 1;
      

      很好。由于您需要消息来一一更改 UI。或者根据需要设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-26
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-06
        • 2017-03-30
        相关资源
        最近更新 更多