NSOperationQueue会留在记忆中多久?

时间:2016-02-23 10:54:33

标签: ios nsoperation nsoperationqueue

假设我在某个类函数的范围内有bgQueue,例如:

- (void)synchronize() {
    NSOperationQueue *bgOperation = [NSOperationQueue new];
   [bgOperation addOperations:@[fetchDataOperation, saveDataOperation, completionOperation] waitUntilFinished:NO];
}

此操作队列是否会保留在内存中,直到包含的所有操作都完成或者在方法范围结束时将从内存中删除?

我想知道操作是否存在于它们所属的内存队列中?

1 个答案:

答案 0 :(得分:2)

我无法在文档中找到一个好的答案,但我建立了一个测试用例来解决它。即使没有引用NSOperationQueue,似乎队列仍然存在,直到所有操作都完成。

以下是示例代码,我在iOS应用中运行runLotsOfPrints()

func runLotsOfPrints() {

    var loopCount = 0
    let maxPrintCount = 10000
    var operations: [NSOperation] = []
    while loopCount < maxPrintCount {

        let newOperation = localOperation()
        newOperation.localNumber = loopCount
        operations.append(newOperation)
        loopCount += 1
    }

    let queue = localOperationQueue()
    queue.addOperations(operations, waitUntilFinished: false)
}

class localOperation: NSOperation {

    var localNumber: Int = 0

    override func main() {
        super.main()
        NSLog("localN - \(self.localNumber)")
    }
}

class localOperationQueue: NSOperationQueue {
    deinit {
        print("deinit - QUEUE")
    }
}

结果日志输出如下:

2016-02-23 10:50:51.388 RobotsAreMyFriends[12363:35784085] localN - 1
2016-02-23 10:50:51.388 RobotsAreMyFriends[12363:35784114] localN - 2
...
2016-02-23 10:50:51.389 RobotsAreMyFriends[12363:35784131] localN - 9998
2016-02-23 10:50:51.388 RobotsAreMyFriends[12363:35784108] localN - 9997
2016-02-23 10:50:51.389 RobotsAreMyFriends[12363:35784113] localN - 9999
2016-02-23 10:50:51.476 RobotsAreMyFriends[12363:35784108] deinit - QUEUE