├── .gitignore ├── ConcurrencyIniOS.playground ├── Pages │ ├── GCD Barrier.xcplaygroundpage │ │ ├── Contents.swift │ │ └── Sources │ │ │ ├── Delay.swift │ │ │ └── Person.swift │ ├── GCD Groups.xcplaygroundpage │ │ └── Contents.swift │ ├── Grand Central Dispatch.xcplaygroundpage │ │ └── Contents.swift │ ├── NSOperation Async.xcplaygroundpage │ │ └── Contents.swift │ ├── NSOperation Dependencies.xcplaygroundpage │ │ ├── Contents.swift │ │ └── Sources │ │ │ └── AsyncOperation.swift │ ├── NSOperation in Practice.xcplaygroundpage │ │ ├── Contents.swift │ │ └── Sources │ │ │ ├── AsyncOperation.swift │ │ │ ├── ImageCell.swift │ │ │ ├── ImageFilters.swift │ │ │ └── ImageLoader.swift │ ├── NSOperation.xcplaygroundpage │ │ └── Contents.swift │ └── NSOperationQueue.xcplaygroundpage │ │ └── Contents.swift ├── Resources │ ├── dark_road_small.jpg │ ├── razeware_64.png │ ├── train_day.jpg │ ├── train_dusk.jpg │ └── train_night.jpg ├── Sources │ ├── Duration.swift │ ├── Graphics │ │ ├── GradientGenerator.swift │ │ └── UIImage+Blur.swift │ ├── NetworkSimulator.swift │ └── TiltShift.swift └── contents.xcplayground ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | ## Playgrounds 31 | timeline.xctimeline 32 | playground.xcworkspace 33 | 34 | # Swift Package Manager 35 | # 36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 37 | # Packages/ 38 | .build/ 39 | 40 | # CocoaPods 41 | # 42 | # We recommend against adding the Pods directory to your .gitignore. However 43 | # you should judge for yourself, the pros and cons are mentioned at: 44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 45 | # 46 | # Pods/ 47 | 48 | # Carthage 49 | # 50 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 51 | # Carthage/Checkouts 52 | 53 | Carthage/Build 54 | 55 | # fastlane 56 | # 57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 58 | # screenshots whenever they are needed. 59 | # For more information about the recommended setup visit: 60 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 61 | 62 | fastlane/report.xml 63 | fastlane/Preview.html 64 | fastlane/screenshots 65 | fastlane/test_output 66 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/GCD Barrier.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ GCD Groups](@previous) 2 | 3 | import Foundation 4 | import XCPlayground 5 | 6 | XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 7 | 8 | //: ## GCD Barriers 9 | //: When you're using asynchronous calls you need to conside thread safety. 10 | //: Consider the following object: 11 | 12 | let nameChangingPerson = Person(firstName: "Alison", lastName: "Anderson") 13 | 14 | //: The `Person` class includes a method to change names: 15 | 16 | nameChangingPerson.changeName(firstName: "Brian", lastName: "Biggles") 17 | nameChangingPerson.name 18 | 19 | //: What happens if you try and use the `changeName(firstName:lastName:)` simulataneously from a concurrent queue? 20 | 21 | let workerQueue = dispatch_queue_create("com.raywenderlich.worker", DISPATCH_QUEUE_CONCURRENT) 22 | let nameChangeGroup = dispatch_group_create() 23 | 24 | let nameList = [("Charlie", "Cheesecake"), ("Delia", "Dingle"), ("Eva", "Evershed"), ("Freddie", "Frost"), ("Gina", "Gregory")] 25 | 26 | for name in nameList { 27 | dispatch_group_async(nameChangeGroup, workerQueue) { 28 | nameChangingPerson.changeName(firstName: name.0, lastName: name.1) 29 | print("Current Name: \(nameChangingPerson.name)") 30 | } 31 | } 32 | 33 | dispatch_group_notify(nameChangeGroup, dispatch_get_main_queue()) { 34 | print("Final name: \(nameChangingPerson.name)") 35 | //XCPlaygroundPage.currentPage.finishExecution() 36 | } 37 | 38 | dispatch_group_wait(nameChangeGroup, DISPATCH_TIME_FOREVER) 39 | 40 | //: __Result:__ `nameChangingPerson` has been left in an inconsistent state. 41 | 42 | 43 | //: ### Dispatch Barrier 44 | //: A barrier allows you add a task to a concurrent queue that will be run in a serial fashion. i.e. it will wait for the currently queued tasks to complete, and prevent any new ones starting. 45 | 46 | class ThreadSafePerson: Person { 47 | 48 | let isolationQueue = dispatch_queue_create("com.raywenderlich.person.isolation", DISPATCH_QUEUE_CONCURRENT) 49 | 50 | override func changeName(firstName firstName: String, lastName: String) { 51 | dispatch_barrier_async(isolationQueue) { 52 | super.changeName(firstName: firstName, lastName: lastName) 53 | } 54 | } 55 | 56 | override var name: String { 57 | var result = "" 58 | dispatch_sync(isolationQueue) { 59 | result = super.name 60 | } 61 | return result 62 | } 63 | } 64 | 65 | 66 | print("\n=== Threadsafe ===") 67 | 68 | let threadSafeNameGroup = dispatch_group_create() 69 | 70 | let threadSafePerson = ThreadSafePerson(firstName: "Anna", lastName: "Adams") 71 | 72 | for name in nameList { 73 | dispatch_group_async(threadSafeNameGroup, workerQueue) { 74 | threadSafePerson.changeName(firstName: name.0, lastName: name.1) 75 | print("Current threadsafe name: \(threadSafePerson.name)") 76 | } 77 | } 78 | 79 | dispatch_group_notify(threadSafeNameGroup, dispatch_get_main_queue()) { 80 | print("Final threadsafe name: \(threadSafePerson.name)") 81 | XCPlaygroundPage.currentPage.finishExecution() 82 | } 83 | 84 | /*: 85 | --- 86 | Hope you enjoyed this playground introduction to concurrency on iOS. Any questions please feel free to shout at me on twitter — I'm [@iwantmyrealname](https://twitter.com/iwantmyrealname). 87 | 88 | —sam 89 | 90 | 91 | ![Razeware](razeware_64.png) 92 | 93 | © Razeware LLC, 2016 94 | */ 95 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/GCD Barrier.xcplaygroundpage/Sources/Delay.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import Foundation 24 | 25 | func randomDelay(maxDuration: Double) { 26 | let randomWait = arc4random_uniform(UInt32(maxDuration * Double(USEC_PER_SEC))) 27 | usleep(randomWait) 28 | } 29 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/GCD Barrier.xcplaygroundpage/Sources/Person.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import Foundation 25 | 26 | public class Person { 27 | private var firstName: String 28 | private var lastName: String 29 | 30 | public init(firstName: String, lastName: String) { 31 | self.firstName = firstName 32 | self.lastName = lastName 33 | } 34 | 35 | public func changeName(firstName firstName: String, lastName: String) { 36 | randomDelay(0.2) 37 | self.firstName = firstName 38 | randomDelay(1) 39 | self.lastName = lastName 40 | } 41 | 42 | public var name: String { 43 | return "\(firstName) \(lastName)" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/GCD Groups.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ Grand Central Dispatch](@previous) 2 | /*: 3 | ## Dispatch Groups 4 | 5 | Dispatch groups are a feature of GCD that allow you to perform an action when a group of GCD operations has completed. This offers a really simple way to keep track of the progress of a set of operations, rather than having to implement something to keep track yourself. 6 | 7 | When you're responsible for dispatching blocks yourself, it's really easy to disptach a block into a particular dispatch group, using the `dispatch_group_*()` family of functions, but the real power comes from being able to wrap existing async functions in dispatch groups. 8 | 9 | In this demo you'll see how you can use dispatch groups to run an action when a set of disparate animations has completed. 10 | */ 11 | import UIKit 12 | import XCPlayground 13 | 14 | //: Create a new animation function on `UIView` that wraps an existing animation function, but now takes a dispatch group as well. 15 | extension UIView { 16 | static func animateWithDuration(duration: NSTimeInterval, animations: () -> Void, group: dispatch_group_t, completion: ((Bool) -> Void)?) { 17 | dispatch_group_enter(group) 18 | animateWithDuration(duration, animations: animations) { (success) in 19 | completion?(success) 20 | dispatch_group_leave(group) 21 | } 22 | } 23 | } 24 | 25 | //: Create a disptach group with `dispatch_group_create()`: 26 | let animationGroup = dispatch_group_create() 27 | 28 | //: The animation uses the following views 29 | let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 30 | view.backgroundColor = UIColor.redColor() 31 | let box = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) 32 | box.backgroundColor = UIColor.yellowColor() 33 | view.addSubview(box) 34 | 35 | XCPlaygroundPage.currentPage.liveView = view 36 | 37 | //: The following completely independent animations now use the dispatch group so that you can determine when all of the animations have completed: 38 | 39 | UIView.animateWithDuration(1, animations: { 40 | box.center = CGPoint(x: 150, y: 150) 41 | }, group: animationGroup, completion: { 42 | _ in 43 | UIView.animateWithDuration(2, animations: { 44 | box.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4)) 45 | }, group: animationGroup, completion: nil) 46 | }) 47 | 48 | UIView.animateWithDuration(4, animations: { () -> Void in 49 | view.backgroundColor = UIColor.blueColor() 50 | }, group: animationGroup, completion: nil) 51 | 52 | 53 | //: `dispatch_group_notify()` allows you to specify a block that will be executed only when all the blocks in that dispatch group have completed: 54 | dispatch_group_notify(animationGroup, dispatch_get_main_queue()) { 55 | print("Animations Completed!") 56 | XCPlaygroundPage.currentPage.finishExecution() 57 | } 58 | 59 | //: [➡ Thread safety with GCD Barriers](@next) 60 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/Grand Central Dispatch.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ NSOperation in Practice](@previous) 2 | /*: 3 | ## GCD Queues 4 | NSOperation queues are built on top of a technology called `libdispatch`, or *Grand Central Dispatch*. This is an advanced open-source technology that underpins concurrent programming on Apple technologies. It uses the now-familiar queuing model to greatly simplify concurrent programming, but is a C-level interface. This can make it slightly more challenging to work with. 5 | */ 6 | import UIKit 7 | import XCPlayground 8 | 9 | XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 10 | /*: 11 | ### Using a Global Queue 12 | iOS has some global queues, where every task eventually ends up being executed. You can use these directly. You need to use the main queue for UI updates. 13 | */ 14 | let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) 15 | let mainQueue = dispatch_get_main_queue() 16 | 17 | //: ### Creating your own Queue 18 | //: Creating your own queues allow you to specify a label, which is super-useful for debugging. 19 | //: You can specify whether the queue is serieal (default) or concurrent (see later). 20 | //: You can also specify the QOS or priority (here be dragons) 21 | let attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0) 22 | let workerQueue = dispatch_queue_create("com.raywenderlich.worker", attr) 23 | 24 | 25 | //: ### Getting the queue name 26 | //: You can't get hold of the "current queue", but you can obtain its name - useful for debugging 27 | func currentQueueName() -> String? { 28 | let label = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) 29 | return String(CString: label, encoding: NSUTF8StringEncoding) 30 | } 31 | 32 | let currentQueue = currentQueueName() 33 | print(currentQueue) 34 | 35 | 36 | //: ### Dispatching work asynchronously 37 | //: Send some work off to be done, and then continue on—don't await a result 38 | print("=== Sending asynchronously to Worker Queue ===") 39 | dispatch_async(workerQueue) { 40 | print("=== ASYNC:: Executing on \(currentQueueName()) ===") 41 | } 42 | print("=== Completed sending asynchronously to worker queue ===\n") 43 | 44 | 45 | 46 | //: ### Dispatching work synchronously 47 | //: Send some work off and wait for it to complete before continuing (here be more dragons) 48 | print("=== Sending SYNChronously to Worker Queue ===") 49 | dispatch_sync(workerQueue) { 50 | print("=== SYNC:: Executing on \(currentQueueName()) ===") 51 | } 52 | 53 | 54 | print("=== Completed sending synchronously to worker queue ===\n") 55 | 56 | 57 | 58 | //: ### Concurrent and serial queues 59 | //: Serial allows one job to be worked on at a time, concurrent multitple 60 | func doComplexWork() { 61 | sleep(1) 62 | print("\(currentQueueName()) :: Done!") 63 | } 64 | 65 | print("=== Starting Serial ===") 66 | dispatch_async(workerQueue, doComplexWork) 67 | dispatch_async(workerQueue, doComplexWork) 68 | dispatch_async(workerQueue, doComplexWork) 69 | dispatch_async(workerQueue, doComplexWork) 70 | 71 | sleep(5) 72 | 73 | let concurrentQueue = dispatch_queue_create("com.raywenderlich.concurrent", DISPATCH_QUEUE_CONCURRENT) 74 | 75 | print("\n=== Starting concurrent ===") 76 | dispatch_async(concurrentQueue, doComplexWork) 77 | dispatch_async(concurrentQueue, doComplexWork) 78 | dispatch_async(concurrentQueue, doComplexWork) 79 | dispatch_async(concurrentQueue, doComplexWork) 80 | 81 | sleep(5) 82 | 83 | XCPlaygroundPage.currentPage.finishExecution() 84 | 85 | 86 | //: [➡ GCD Groups](@next) 87 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation Async.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ NSOperationQueue](@previous) 2 | /*: 3 | ## Wrapping Asynchronous Functions in NSOperation 4 | 5 | The approach you've seen thus far to wrapping functionality in `NSOperation` only works provided you can guarantee that all the work has been completed when the `main()` method returns. This is not the case if you're wrapping asynchronous functions, which return immediately, and return their result at a later point. 6 | 7 | `NSOperation` has support for this, but requires that you manage the state manually. The following KVO properties must now be kept up-to-date with the operation status: 8 | - `ready` 9 | - `executing` 10 | - `finished` 11 | 12 | In order to make this task easier, `AsyncOperation` is a custom subclass of `NSOperation` that handles the state change automatically, and in a slightly more _Swift-like_ manner. This reduces wrapping an asynchronous function to the following: 13 | 14 | 1. Subclass `AsyncOperation`. 15 | 2. Override `main()` and call your async function. 16 | 3. Change the `state` property of the `AsyncOperation` subclass to `.Finished` in the async callback. 17 | 18 | - important: 19 | Step 3 of these instructions is *extremely* important - it's how the queue responsible for running the operation can tell that it has completed. Otherwise it'll sit uncompleted for eternity. 20 | */ 21 | import UIKit 22 | 23 | 24 | /*: 25 | The subclass adds a `state` property, and ensures that the appropriate KVO notifications are sent when the value is updated. This is integral to how `NSOperationQueue` manages its operations 26 | */ 27 | class AsyncOperation: NSOperation { 28 | enum State: String { 29 | case Ready, Executing, Finished 30 | 31 | private var keyPath: String { 32 | return "is" + rawValue 33 | } 34 | } 35 | 36 | var state = State.Ready { 37 | willSet { 38 | willChangeValueForKey(newValue.keyPath) 39 | willChangeValueForKey(state.keyPath) 40 | } 41 | didSet { 42 | didChangeValueForKey(oldValue.keyPath) 43 | didChangeValueForKey(state.keyPath) 44 | } 45 | } 46 | } 47 | 48 | /*: 49 | Each of the state properties inherited from `NSOperation` are then overridden to defer to the new `state` property. 50 | 51 | The `asynchronous` property must be set to `true` to tell the system that you'll be managing the state manually. 52 | 53 | You also override `start()` and `cancel()` to wire in the new `state` property. 54 | */ 55 | extension AsyncOperation { 56 | // NSOperation Overrides 57 | override var ready: Bool { 58 | return super.ready && state == .Ready 59 | } 60 | 61 | override var executing: Bool { 62 | return state == .Executing 63 | } 64 | 65 | override var finished: Bool { 66 | return state == .Finished 67 | } 68 | 69 | override var asynchronous: Bool { 70 | return true 71 | } 72 | 73 | override func start() { 74 | if cancelled { 75 | state = .Finished 76 | return 77 | } 78 | main() 79 | state = .Executing 80 | } 81 | 82 | override func cancel() { 83 | state = .Finished 84 | } 85 | } 86 | 87 | 88 | /*: 89 | Wrapping an asynchronous function then becomes as simple as overriding the `main()` function, remembering to set the `state` parameter on completion: 90 | */ 91 | class ImageLoadOperation: AsyncOperation { 92 | var inputName: String? 93 | var outputImage: UIImage? 94 | 95 | override func main() { 96 | duration { 97 | simulateNetworkImageLoadAsync(self.inputName, callback: { (image) in 98 | self.outputImage = image 99 | self.state = .Finished 100 | }) 101 | } 102 | } 103 | } 104 | 105 | //: This operation can then be used in the same way as any other `NSOperation`: 106 | let queue = NSOperationQueue() 107 | 108 | let imageLoad = ImageLoadOperation() 109 | imageLoad.inputName = "train_dusk.jpg" 110 | 111 | queue.addOperation(imageLoad) 112 | 113 | duration { 114 | queue.waitUntilAllOperationsAreFinished() 115 | } 116 | 117 | imageLoad.outputImage 118 | 119 | //: [➡ NSOperation Dependencies](@next) 120 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation Dependencies.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | /*: 3 | ## Chaining NSOperations 4 | 5 | Standalone operations are useful, but the true power from `NSOperation` comes from when you chain them together, building up a complex workflow from small parts. 6 | 7 | In order to achieve this, you need to be able to pass the result of one operation to the next in the chain. This can be achieved using the `dependencies` property of `NSOperation`. 8 | 9 | In this demo, you have two operations - one the same filtering one you've been using, and the other one that simulates loading the source image over a network. 10 | 11 | - example: 12 | You can imagine that you might need to build up a chain that involves even more steps: 13 | - Retrieve source name from a data store 14 | - Download an image from a network 15 | - Decompress the image using a custom decompressor 16 | - Apply a filter to the image 17 | - Apply a second filter to the image 18 | - Display the image 19 | \ 20 | Each of these tasks could be modelled as an `NSOperation`, and the dependencies architecture would ensure that each operation will only begin once the appropriate data has been produced from a previous operation. 21 | 22 | This approach allows you to break down complex tasks into smaller, reusable operations which compose together nicely. It can lead to cleaner code. However, be warned that as with any asynchronous code, debugging can become more challenging. 23 | 24 | - note: 25 | More than one operation can depend on another, so you can actually build a dependency graph - you're not limited to a simple chain. The great part of this is that you don't have to manage the scheduling of any of these - the operation queue handles it all for you. 26 | */ 27 | import UIKit 28 | 29 | //: An operation that loads the file "over the network": 30 | class ImageLoadOperation: AsyncOperation { 31 | var inputName: String? 32 | var outputImage: UIImage? 33 | 34 | override func main() { 35 | simulateNetworkImageLoadAsync(self.inputName, callback: { (image) in 36 | self.outputImage = image 37 | self.state = .Finished 38 | }) 39 | } 40 | } 41 | 42 | //: The same filtering operation you saw before. The `main()` method now attempts to find an input image in its dependencies if the `inputImage` property hasn't already been set. 43 | class TiltShiftOperation: NSOperation { 44 | var inputImage: UIImage? 45 | var outputImage: UIImage? 46 | 47 | override func main() { 48 | if let dependencyImageProvider = dependencies 49 | .filter({ $0 is FilterDataProvider}) 50 | .first as? FilterDataProvider 51 | where inputImage == .None { 52 | inputImage = dependencyImageProvider.outputImage 53 | } 54 | outputImage = tiltShift(inputImage) 55 | } 56 | } 57 | 58 | 59 | //: Rather than coding directly to concrete implementations, define a protocol that represents _"an object that can provide data to an image filter"_. This makes the code that searches dependencies far less brittle. 60 | protocol FilterDataProvider { 61 | var outputImage: UIImage? { get } 62 | } 63 | 64 | extension ImageLoadOperation: FilterDataProvider { 65 | 66 | } 67 | 68 | 69 | /*: 70 | To add a dependency to an `NSOperation` object, use the `addDependency()` method. 71 | However, it's a rare case when a custom operator can make the code easier to read. 72 | - important: 73 | Heed all the usual warnings about custom operators. This is a situation where they can offer genuine clarity, but that isn't often the case. 74 | */ 75 | infix operator |> { associativity left precedence 150 } 76 | func |>(lhs: NSOperation, rhs: NSOperation) -> NSOperation { 77 | rhs.addDependency(lhs) 78 | return rhs 79 | } 80 | 81 | 82 | //: Create the relevant operations 83 | let imageLoad = ImageLoadOperation() 84 | let filter = TiltShiftOperation() 85 | 86 | //: Set the input parameter on the image loading operation: 87 | imageLoad.inputName = "train_day.jpg" 88 | 89 | //: And set the dependency chain 90 | imageLoad |> filter 91 | 92 | //: Add both operations to the operation queue 93 | let queue = NSOperationQueue() 94 | duration { 95 | queue.addOperations([imageLoad, filter], waitUntilFinished: true) 96 | } 97 | 98 | 99 | filter.outputImage 100 | 101 | 102 | //: [➡ NSOperation in Practice](@next) 103 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation Dependencies.xcplaygroundpage/Sources/AsyncOperation.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import Foundation 25 | 26 | public class AsyncOperation: NSOperation { 27 | public enum State: String { 28 | case Ready, Executing, Finished 29 | 30 | private var keyPath: String { 31 | return "is" + rawValue 32 | } 33 | } 34 | 35 | public var state = State.Ready { 36 | willSet { 37 | willChangeValueForKey(newValue.keyPath) 38 | willChangeValueForKey(state.keyPath) 39 | } 40 | didSet { 41 | didChangeValueForKey(oldValue.keyPath) 42 | didChangeValueForKey(state.keyPath) 43 | } 44 | } 45 | } 46 | 47 | 48 | extension AsyncOperation { 49 | // NSOperation Overrides 50 | override public var ready: Bool { 51 | return super.ready && state == .Ready 52 | } 53 | 54 | override public var executing: Bool { 55 | return state == .Executing 56 | } 57 | 58 | override public var finished: Bool { 59 | return state == .Finished 60 | } 61 | 62 | override public var asynchronous: Bool { 63 | return true 64 | } 65 | 66 | override public func start() { 67 | if cancelled { 68 | state = .Finished 69 | return 70 | } 71 | 72 | main() 73 | state = .Executing 74 | } 75 | 76 | public override func cancel() { 77 | state = .Finished 78 | } 79 | } -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation in Practice.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ Chaining NSOperations](@previous) 2 | /*: 3 | ## NSOperations in Practice 4 | 5 | You've seen how powerful `NSOperation` is, but not really seen it fix a real-world problem. 6 | 7 | This playground page demonstrates how you can use `NSOperation` to load and filter images for display in a table view, whilst maintaining the smooth scroll effect you expect from table views. 8 | 9 | This is a common problem, and comes from the fact that if you attempt expensive operations synchronously, you'll block the main queue (thread). Since this is used for rendering the UI, you cause your app to become unresponsive - temporarily freezing. 10 | 11 | The solution is to move data loading off into the background, which can be achieved easily with `NSOperation`. 12 | 13 | */ 14 | import UIKit 15 | import XCPlayground 16 | 17 | let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 320, height: 720)) 18 | tableView.registerClass(ImageCell.self, forCellReuseIdentifier: "ImageCell") 19 | XCPlaygroundPage.currentPage.liveView = tableView 20 | tableView.rowHeight = 250 21 | 22 | 23 | //: `ImageProvider` is a class that is responsible for loading and processing an image. It creates the relevant operations, chains them together, pops them on a queue and then ensures that the output is passed back appropriately 24 | class ImageProvider { 25 | 26 | let queue = NSOperationQueue() 27 | 28 | init(imageName: String, completion: (UIImage?) -> ()) { 29 | let loadOp = ImageLoadOperation() 30 | let tiltShiftOp = TiltShiftOperation() 31 | let outputOp = ImageOutputOperation() 32 | 33 | loadOp.inputName = imageName 34 | outputOp.completion = completion 35 | 36 | loadOp |> tiltShiftOp |> outputOp 37 | 38 | queue.addOperations([loadOp, tiltShiftOp, outputOp], waitUntilFinished: false) 39 | } 40 | 41 | func cancel() { 42 | queue.cancelAllOperations() 43 | } 44 | } 45 | 46 | //: `DataSource` is a class that represents the table's datasource and delegate 47 | class DataSource: NSObject { 48 | var imageNames = [String]() 49 | var imageProviders = [NSIndexPath : ImageProvider]() 50 | } 51 | 52 | //: Possibly the simplest implementation of `UITableViewDataSource`: 53 | extension DataSource: UITableViewDataSource { 54 | func numberOfSectionsInTableView(tableView: UITableView) -> Int { 55 | return 1 56 | } 57 | 58 | func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 59 | return imageNames.count 60 | } 61 | 62 | func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 63 | return tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) 64 | } 65 | } 66 | 67 | extension DataSource: UITableViewDelegate { 68 | func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 69 | if let cell = cell as? ImageCell { 70 | let provider = ImageProvider(imageName: imageNames[indexPath.row], completion: { (image) in 71 | cell.transitionToImage(image) 72 | self.imageProviders.removeValueForKey(indexPath) 73 | }) 74 | imageProviders[indexPath] = provider 75 | } 76 | } 77 | 78 | func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 79 | if let cell = cell as? ImageCell { 80 | cell.transitionToImage(.None) 81 | } 82 | if let provider = imageProviders[indexPath] { 83 | provider.cancel() 84 | imageProviders.removeValueForKey(indexPath) 85 | } 86 | } 87 | } 88 | 89 | //: Create a datasource and provide a list of images to display 90 | let ds = DataSource() 91 | ds.imageNames = ["dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg", "dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg", "dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg", "dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg"] 92 | 93 | tableView.dataSource = ds 94 | tableView.delegate = ds 95 | 96 | /*: 97 | - note: 98 | This implementation for a table view is not complete, but instead meant to demonstrate how you can use `NSOperation` to improve the scrolling performance. 99 | 100 | [➡ Grand Central Dispatch](@next) 101 | */ 102 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation in Practice.xcplaygroundpage/Sources/AsyncOperation.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import Foundation 24 | 25 | public class AsyncOperation: NSOperation { 26 | public enum State: String { 27 | case Ready, Executing, Finished 28 | 29 | private var keyPath: String { 30 | return "is" + rawValue 31 | } 32 | } 33 | 34 | public var state = State.Ready { 35 | willSet { 36 | willChangeValueForKey(newValue.keyPath) 37 | willChangeValueForKey(state.keyPath) 38 | } 39 | didSet { 40 | didChangeValueForKey(oldValue.keyPath) 41 | didChangeValueForKey(state.keyPath) 42 | } 43 | } 44 | } 45 | 46 | 47 | extension AsyncOperation { 48 | // NSOperation Overrides 49 | override public var ready: Bool { 50 | return super.ready && state == .Ready 51 | } 52 | 53 | override public var executing: Bool { 54 | return state == .Executing 55 | } 56 | 57 | override public var finished: Bool { 58 | return state == .Finished 59 | } 60 | 61 | override public var asynchronous: Bool { 62 | return true 63 | } 64 | 65 | override public func start() { 66 | if cancelled { 67 | state = .Finished 68 | return 69 | } 70 | 71 | main() 72 | state = .Executing 73 | } 74 | 75 | public override func cancel() { 76 | state = .Finished 77 | } 78 | } 79 | 80 | 81 | infix operator |> { associativity left precedence 150 } 82 | public func |>(lhs: NSOperation, rhs: NSOperation) -> NSOperation { 83 | rhs.addDependency(lhs) 84 | return rhs 85 | } 86 | 87 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation in Practice.xcplaygroundpage/Sources/ImageCell.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public class ImageCell: UITableViewCell { 26 | public var fullImage: UIImage? { 27 | didSet { 28 | fullImageView?.image = fullImage 29 | } 30 | } 31 | 32 | public func transitionToImage(image: UIImage?) { 33 | NSOperationQueue.mainQueue().addOperationWithBlock { 34 | if image == nil { 35 | self.fullImageView?.alpha = 0 36 | } else { 37 | self.fullImageView?.image = image 38 | UIView.animateWithDuration(0.4, animations: { 39 | self.fullImageView?.alpha = 1 40 | }) 41 | } 42 | } 43 | } 44 | 45 | var fullImageView: UIImageView? 46 | 47 | required public init?(coder aDecoder: NSCoder) { 48 | super.init(coder: aDecoder) 49 | sharedInit() 50 | } 51 | 52 | override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { 53 | super.init(style: style, reuseIdentifier: reuseIdentifier) 54 | sharedInit() 55 | } 56 | 57 | 58 | func sharedInit() { 59 | fullImageView = UIImageView(image: fullImage) 60 | 61 | guard let fullImageView = fullImageView else { return } 62 | addSubview(fullImageView) 63 | 64 | fullImageView.contentMode = .ScaleAspectFill 65 | fullImageView.translatesAutoresizingMaskIntoConstraints = false 66 | fullImageView.clipsToBounds = true 67 | 68 | NSLayoutConstraint.activateConstraints([ 69 | fullImageView.bottomAnchor.constraintEqualToAnchor(bottomAnchor), 70 | fullImageView.topAnchor.constraintEqualToAnchor(topAnchor), 71 | fullImageView.leadingAnchor.constraintEqualToAnchor(leadingAnchor), 72 | fullImageView.trailingAnchor.constraintEqualToAnchor(trailingAnchor) 73 | ]) 74 | 75 | } 76 | 77 | } 78 | 79 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation in Practice.xcplaygroundpage/Sources/ImageFilters.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import UIKit 25 | 26 | 27 | public class TiltShiftOperation: NSOperation { 28 | public var inputImage: UIImage? 29 | public var outputImage: UIImage? 30 | 31 | public override func main() { 32 | if let dependencyImageProvider = dependencies 33 | .filter({ $0 is FilterDataProvider }) 34 | .first as? FilterDataProvider 35 | where inputImage == .None { 36 | inputImage = dependencyImageProvider.outputImage 37 | } 38 | 39 | outputImage = tiltShift(inputImage) 40 | } 41 | } 42 | 43 | public class ImageOutputOperation: NSOperation { 44 | public var inputImage: UIImage? 45 | public var completion: ((UIImage?) -> ())? 46 | 47 | public override func main() { 48 | guard let completion = completion else { return } 49 | if let dependencyImageProvider = dependencies 50 | .filter({ $0 is FilterDataProvider }) 51 | .first as? FilterDataProvider 52 | where inputImage == .None { 53 | inputImage = dependencyImageProvider.outputImage 54 | } 55 | 56 | completion(inputImage) 57 | } 58 | } 59 | 60 | 61 | 62 | public protocol FilterDataProvider { 63 | var outputImage: UIImage? { get } 64 | } 65 | 66 | extension ImageLoadOperation: FilterDataProvider { 67 | 68 | } 69 | 70 | extension TiltShiftOperation: FilterDataProvider { 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation in Practice.xcplaygroundpage/Sources/ImageLoader.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public class ImageLoadOperation: AsyncOperation { 26 | public var inputName: String? 27 | public var outputImage: UIImage? 28 | 29 | public override func main() { 30 | simulateNetworkImageLoadAsync(self.inputName, callback: { (image) in 31 | self.outputImage = image 32 | self.state = .Finished 33 | }) 34 | } 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperation.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /*: 2 | # Concurrency in iOS 3 | ## iOSCon 2016 4 | ## Sam Davies · [@iwantmyrealname](https://twitter.com/iwantmyrealname) 5 | 6 | This playground forms the basis of a talk presented at [iOSCon 2016](https://skillsmatter.com/conferences/7598-ioscon-2016-the-conference-for-ios-and-swift-developers). 7 | 8 | The following represents the pages contained within this playground 9 | 10 | - [NSOperation](NSOperation) 11 | - [NSOperationQueue](NSOperationQueue) 12 | - [Wrapping Aysnc Functions in NSOperation](NSOperation%20Async) 13 | - [Inter-Operation Dependencies](NSOperation%20Dependencies) 14 | - [NSOperation in Practice](NSOperation%20in%20Practice) 15 | - [Grand Central Dispatch](Grand%20Central%20Dispatch) 16 | - [GCD Groups](GCD%20Groups) 17 | - [GCD Barrier](GCD%20Barrier) 18 | 19 | --- 20 | 21 | ## NSOperation 22 | 23 | `NSOperation` is a high-level abstraction that represents _"a unit of work"_. You can use this to wrap some sort of functionality, and then pass this off to be executed concurrently. 24 | */ 25 | 26 | import UIKit 27 | 28 | //: `tiltShift()` is a function that applies a tilt-shift-like filter to a `UIImage`, and as such it's rather (artificially) slow. 29 | 30 | let image = UIImage(named: "dark_road_small.jpg") 31 | duration { 32 | let result = tiltShift(image) 33 | } 34 | 35 | var outputImage: UIImage? 36 | 37 | //: You can use the `NSBlockOperation` subclass of `NSOperation` to easily wrap some functionality. 38 | 39 | let myFirstOperation = NSBlockOperation { 40 | outputImage = tiltShift(image) 41 | } 42 | 43 | //: You can then execute this operation with the `start()` method: 44 | myFirstOperation.start() 45 | 46 | 47 | outputImage 48 | 49 | 50 | /*: 51 | Although `NSBlockOperation` has a very low bar for entry, it's not especially flexible. It's more usual to subclass `NSOperation` directly, and specialise it to particular functionality. 52 | 53 | When subclassing, create properties for input and output objects, and then override the `main()` method to perform the work. 54 | */ 55 | class TiltShiftOperation: NSOperation { 56 | var inputImage: UIImage? 57 | var outputImage: UIImage? 58 | 59 | override func main() { 60 | outputImage = tiltShift(inputImage) 61 | } 62 | } 63 | 64 | let mySecondOperation = TiltShiftOperation() 65 | mySecondOperation.inputImage = image 66 | 67 | 68 | /*: 69 | Once you've created an instance of the operation, and set the input value, you can go ahead and call `start()` to kick off the execution. 70 | 71 | - note: 72 | Calling `start()` might seem a little strange, but don't worry - you won't be doing it for long... 73 | 74 | */ 75 | mySecondOperation.start() 76 | 77 | mySecondOperation.outputImage 78 | 79 | 80 | //: [➡NSOperationQueue](NSOperationQueue) 81 | 82 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Pages/NSOperationQueue.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /*: 2 | [⬅ NSOperation](@previous) 3 | 4 | ## NSOperationQueue 5 | 6 | There's not a lot of point of carefully wrapping up complex functionality in `NSOperation` object if you then have to call `start()` on each of them to actually begin execution. 7 | 8 | Enter `NSOperationQueue`, which manages the execution of one or more `NSOperation` objects. Rather than having to handle threads directly, you instead pass your operations to a queue to be executed at the system's discretion. A queue can be configured to allow concurrent execution of the operations in the queue. 9 | 10 | */ 11 | 12 | import UIKit 13 | 14 | 15 | //: Using the same tilt-shift operation, this time you've got a set of images rather than just one: 16 | let imageNames = ["dark_road_small", "train_day", "train_dusk", "train_night"] 17 | let images = imageNames.flatMap { UIImage(named: "\($0).jpg") } 18 | images 19 | 20 | class TiltShiftOperation: NSOperation { 21 | var inputImage: UIImage? 22 | var outputImage: UIImage? 23 | 24 | override func main() { 25 | outputImage = tiltShift(inputImage) 26 | } 27 | } 28 | 29 | 30 | //: Creating a queue is simple - using the default constructor: 31 | let queue = NSOperationQueue() 32 | 33 | var operations = [TiltShiftOperation]() 34 | 35 | /*: 36 | Use the `addOperation()` method on `NSOperationQueue` to add each operation to the queue. 37 | 38 | - important: 39 | Adding operations to a queue is really "cheap"; although the operations can start executing as soon as they arrive on the queue, adding them is completely asynchronous. 40 | \ 41 | You can see that here, with the result of the `duration` function: 42 | 43 | */ 44 | duration { 45 | for image in images { 46 | let op = TiltShiftOperation() 47 | op.inputImage = image 48 | operations += [op] 49 | 50 | queue.addOperation(op) 51 | } 52 | } 53 | 54 | /*: 55 | * experiment: 56 | You can control the maximum number of operations that a queue can execute simultaneously with the `maxConcurrentOperationCount` property. Setting this to `1` makes the queue a *serial* queue. 57 | \ 58 | \ 59 | Try changing the value of this property below to see how it affects the time it takes for the queue to finish processing all operations 60 | */ 61 | queue.maxConcurrentOperationCount = 2 62 | 63 | duration { 64 | queue.waitUntilAllOperationsAreFinished() 65 | } 66 | 67 | 68 | //: Check that all operations have filtered the image as expected 69 | let output = operations.flatMap { $0.outputImage } 70 | output 71 | 72 | //: [➡ NSOperation Async](@next) 73 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Resources/dark_road_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/iOSConcurrency/e62e6eda0402e7cf9d310e7c940d50508cf139c3/ConcurrencyIniOS.playground/Resources/dark_road_small.jpg -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Resources/razeware_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/iOSConcurrency/e62e6eda0402e7cf9d310e7c940d50508cf139c3/ConcurrencyIniOS.playground/Resources/razeware_64.png -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Resources/train_day.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/iOSConcurrency/e62e6eda0402e7cf9d310e7c940d50508cf139c3/ConcurrencyIniOS.playground/Resources/train_day.jpg -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Resources/train_dusk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/iOSConcurrency/e62e6eda0402e7cf9d310e7c940d50508cf139c3/ConcurrencyIniOS.playground/Resources/train_dusk.jpg -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Resources/train_night.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/iOSConcurrency/e62e6eda0402e7cf9d310e7c940d50508cf139c3/ConcurrencyIniOS.playground/Resources/train_night.jpg -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Sources/Duration.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import Foundation 24 | 25 | public func duration(block: () -> ()) -> NSTimeInterval { 26 | let startTime = NSDate() 27 | block() 28 | return NSDate().timeIntervalSinceDate(startTime) 29 | } -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Sources/Graphics/GradientGenerator.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | func topAndBottomGradient(size: CGSize, clearLocations: [CGFloat] = [0.35, 0.65], innerIntensity: CGFloat = 0.5) -> UIImage { 26 | 27 | let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, 0, CGColorSpaceCreateDeviceGray(), CGImageAlphaInfo.None.rawValue) 28 | 29 | let colors = [ 30 | UIColor.whiteColor(), 31 | UIColor(white: innerIntensity, alpha: 1.0), 32 | UIColor.blackColor(), 33 | UIColor(white: innerIntensity, alpha: 1.0), 34 | UIColor.whiteColor() 35 | ].map { $0.CGColor } 36 | let colorLocations : [CGFloat] = [0, clearLocations[0], (clearLocations[0] + clearLocations[1]) / 2.0, clearLocations[1], 1] 37 | 38 | let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceGray(), colors, colorLocations) 39 | 40 | let startPoint = CGPoint(x: 0, y: 0) 41 | let endPoint = CGPoint(x: 0, y: size.height) 42 | CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, CGGradientDrawingOptions()) 43 | 44 | let cgImage = CGBitmapContextCreateImage(context) 45 | 46 | return UIImage(CGImage: cgImage!) 47 | } 48 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Sources/Graphics/UIImage+Blur.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | import Accelerate 25 | 26 | extension UIImage { 27 | public func applyBlurWithRadius(blurRadius: CGFloat, maskImage: UIImage? = nil) -> UIImage? { 28 | // Check pre-conditions. 29 | if (size.width < 1 || size.height < 1) { 30 | print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") 31 | return nil 32 | } 33 | if self.CGImage == nil { 34 | print("*** error: image must be backed by a CGImage: \(self)") 35 | return nil 36 | } 37 | if maskImage != nil && maskImage!.CGImage == nil { 38 | print("*** error: maskImage must be backed by a CGImage: \(maskImage)") 39 | return nil 40 | } 41 | 42 | let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) 43 | let screenScale = UIScreen.mainScreen().scale 44 | let imageRect = CGRect(origin: CGPointZero, size: size) 45 | var effectImage = self 46 | 47 | let hasBlur = blurRadius > __FLT_EPSILON__ 48 | 49 | if hasBlur { 50 | func createEffectBuffer(context: CGContext) -> vImage_Buffer { 51 | let data = CGBitmapContextGetData(context) 52 | let width = vImagePixelCount(CGBitmapContextGetWidth(context)) 53 | let height = vImagePixelCount(CGBitmapContextGetHeight(context)) 54 | let rowBytes = CGBitmapContextGetBytesPerRow(context) 55 | 56 | return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) 57 | } 58 | 59 | UIGraphicsBeginImageContextWithOptions(size, false, screenScale) 60 | let effectInContext = UIGraphicsGetCurrentContext()! 61 | 62 | CGContextScaleCTM(effectInContext, 1.0, -1.0) 63 | CGContextTranslateCTM(effectInContext, 0, -size.height) 64 | CGContextDrawImage(effectInContext, imageRect, self.CGImage) 65 | 66 | var effectInBuffer = createEffectBuffer(effectInContext) 67 | 68 | 69 | UIGraphicsBeginImageContextWithOptions(size, false, screenScale) 70 | let effectOutContext = UIGraphicsGetCurrentContext()! 71 | 72 | var effectOutBuffer = createEffectBuffer(effectOutContext) 73 | 74 | 75 | if hasBlur { 76 | // A description of how to compute the box kernel width from the Gaussian 77 | // radius (aka standard deviation) appears in the SVG spec: 78 | // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement 79 | // 80 | // For larger values of 's' (s >= 2.0), an approximation can be used: Three 81 | // successive box-blurs build a piece-wise quadratic convolution kernel, which 82 | // approximates the Gaussian kernel to within roughly 3%. 83 | // 84 | // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) 85 | // 86 | // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. 87 | // 88 | 89 | let inputRadius = blurRadius * screenScale 90 | var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5)) 91 | if radius % 2 != 1 { 92 | radius += 1 // force radius to be odd so that the three box-blur methodology works. 93 | } 94 | 95 | let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) 96 | 97 | vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) 98 | vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) 99 | vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) 100 | } 101 | 102 | effectImage = UIGraphicsGetImageFromCurrentImageContext() 103 | 104 | UIGraphicsEndImageContext() 105 | UIGraphicsEndImageContext() 106 | } 107 | 108 | // Set up output context. 109 | UIGraphicsBeginImageContextWithOptions(size, false, screenScale) 110 | let outputContext = UIGraphicsGetCurrentContext() 111 | CGContextScaleCTM(outputContext, 1.0, -1.0) 112 | CGContextTranslateCTM(outputContext, 0, -size.height) 113 | 114 | // Draw base image. 115 | CGContextDrawImage(outputContext, imageRect, self.CGImage) 116 | 117 | // Draw effect image. 118 | if hasBlur { 119 | CGContextSaveGState(outputContext) 120 | if let image = maskImage { 121 | //CGContextClipToMask(outputContext, imageRect, image.CGImage); 122 | let effectCGImage = CGImageCreateWithMask(effectImage.CGImage, image.CGImage) 123 | if let effectCGImage = effectCGImage { 124 | effectImage = UIImage(CGImage: effectCGImage) 125 | } 126 | } 127 | CGContextDrawImage(outputContext, imageRect, effectImage.CGImage) 128 | CGContextRestoreGState(outputContext) 129 | } 130 | 131 | // Output image is ready. 132 | let outputImage = UIGraphicsGetImageFromCurrentImageContext() 133 | UIGraphicsEndImageContext() 134 | 135 | return outputImage 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Sources/NetworkSimulator.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public func simulateNetworkImageLoad(named: String?) -> UIImage? { 26 | sleep(1) 27 | guard let named = named else { return .None } 28 | return UIImage(named: named) 29 | } 30 | 31 | 32 | public func simulateNetworkImageLoadAsync(named: String?, callback: (UIImage?) -> ()) { 33 | NSOperationQueue().addOperationWithBlock { 34 | let image = simulateNetworkImageLoad(named) 35 | callback(image) 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/Sources/TiltShift.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public func tiltShift(image: UIImage?) -> UIImage? { 26 | guard let image = image else { return .None } 27 | sleep(1) 28 | let mask = topAndBottomGradient(image.size) 29 | return image.applyBlurWithRadius(6, maskImage: mask) 30 | } 31 | 32 | func tiltShiftAsync(image: UIImage?, callback: (UIImage?) ->()) { 33 | NSOperationQueue().addOperationWithBlock { 34 | let result = tiltShift(image) 35 | callback(result) 36 | } 37 | } -------------------------------------------------------------------------------- /ConcurrencyIniOS.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Razeware LLC 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # iOS Concurrency 2 | 3 | This repo contains a playground that demonstrates the Apple-based approaches to concurrency applicable to iOS. 4 | 5 | It forms the basis of talks given at: 6 | 7 | - iOS Con 2016 8 | 9 | If you'd like to receive this info as a talk at your event, gimme a shout. 10 | 11 | Any problems, let me know 12 | 13 | —sam 14 | [@iwantmyrealname](https://twitter.com/iwantmyrealname) 15 | --------------------------------------------------------------------------------