Skip to content

Commit 122933f

Browse files
dannliulxbndr
authored andcommitted
Fix BlockOperation with multiple execution blocks
Steps: 1. Create BlockOperation with an init block. 2. Add another one with addExecutionBlock. 3. Access the executionBlocks property, it contains 3 blocks.
1 parent 15214a4 commit 122933f

File tree

2 files changed

+21
-11
lines changed

2 files changed

+21
-11
lines changed

Sources/Foundation/Operation.swift

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -668,22 +668,16 @@ open class BlockOperation : Operation {
668668
}
669669
_lock()
670670
defer { _unlock() }
671-
if _block == nil && _executionBlocks == nil {
671+
if _block == nil {
672672
_block = block
673+
} else if _executionBlocks == nil {
674+
_executionBlocks = [block]
673675
} else {
674-
if _executionBlocks == nil {
675-
if let existing = _block {
676-
_executionBlocks = [existing, block]
677-
} else {
678-
_executionBlocks = [block]
679-
}
680-
} else {
681-
_executionBlocks?.append(block)
682-
}
676+
_executionBlocks?.append(block)
683677
}
684678
}
685679

686-
open var executionBlocks: [@convention(block) () -> Void] {
680+
open var executionBlocks: [() -> Void] {
687681
get {
688682
_lock()
689683
defer { _unlock() }

Tests/Foundation/Tests/TestOperationQueue.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class TestOperationQueue : XCTestCase {
4040
("test_CustomOperationReady", test_CustomOperationReady),
4141
("test_DependencyCycleBreak", test_DependencyCycleBreak),
4242
("test_Lifecycle", test_Lifecycle),
43+
("test_BlockOperationAddExecutionBlock", test_BlockOperationAddExecutionBlock),
4344
]
4445
}
4546

@@ -699,6 +700,21 @@ class TestOperationQueue : XCTestCase {
699700
Thread.sleep(forTimeInterval: 1) // Let queue to be deallocated
700701
XCTAssertNil(weakQueue, "Queue should be deallocated at this point")
701702
}
703+
704+
func test_BlockOperationAddExecutionBlock() {
705+
var msgOperations = [String]()
706+
let blockOperation = BlockOperation {
707+
msgOperations.append("block1 executed")
708+
}
709+
blockOperation.addExecutionBlock {
710+
msgOperations.append("block2 executed")
711+
}
712+
XCTAssert(blockOperation.executionBlocks.count == 2)
713+
let queue = OperationQueue()
714+
queue.addOperation(blockOperation)
715+
queue.waitUntilAllOperationsAreFinished()
716+
XCTAssertEqual(msgOperations, ["block1 executed", "block2 executed"])
717+
}
702718
}
703719

704720
class AsyncOperation: Operation {

0 commit comments

Comments
 (0)