- [NSRunLoop runUntilDate:]消耗100%的CPU

时间:2015-03-16 15:20:33

标签: ios multithreading nsrunloop external-accessory

我正在构建一个与外部附件接口的应用程序(因此使用ExternalAccessory框架)。

此接口的一部分是等待外部设备的输入/输出流发生事件。

为此,我使用一个线程,并在NSRunLoop中阻止它,以确保它一直等待事件。

- (void)eventThreadSelector
{
    // Setting up the environment
    self.session = <got the EASession>;

    self.inputStream = [self.session inputStream];
    self.inputStream.delegate = self;
    [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream open];

    self.outputStream = [self.session outputStream];
    self.outputStream.delegate = self;
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream open];

    // Waiting for events coming from the NSStreams
    while (![[NSThread currentThread] isCancelled]) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.1]];
    }

    // When the device is unplugged, 
    [self.inputStream close];
    [self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    self.inputStream.delegate = nil;
    self.inputStream = nil;

    [self.outputStream close];
    [self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    self.outputStream.delegate = nil;
    self.outputStream = nil;

    self.session = nil;
}

- (void)accessoryDidDisconnect:(EAAccessory *)accessory
{
    DDLogVerbose(@"EID: Got accessoryDidDisconnect notification on main thread? %i", [[NSThread currentThread] isMainThread]);

    [self.eventThread cancel];
    self.eventThread = nil;
}

到目前为止,所有这些都很有效:)但有一件事我无法解决。

当我拔下外部设备时,处理器会短暂跳至100%及以上。我做了一些调查,这似乎与NSRunLoop有关。该CPU峰值对UI产生负面影响:(

如何避免此处理器使用率峰值?

0 个答案:

没有答案