Kodeco Forums

Video Tutorial: Introducing Concurrency Part 3: Asynchronous Operations

Learn how to use an NSOperation to wrap an asynchronous function such as a network call.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4034-introducing-concurrency/lessons/4

These tutorials have been super helpful to me in my job, especially this one. Thanks to Sam and Ray Wenderlich for producing such rich and useful iOS content

My take on “Asynchronous Operations” video:
I got confused with the usage of Asynchronous and Concurrent throughout the video.

For a normal operation running on an nsoperationqueue, aren’t those operations running concurrently as well given that main() starts a new thread to execute the code in main() and returns immediately? ( Here I am assuming that the operation queue has mxConcurrentOperations value set to >1 )

For asynchronous operation on other hand, the main code itself runs in a different thread than the thread created to execute the main() code and hence we need manual management of the state. So I would argue that the abstractOperation that you have created is an AsynchronousOperation rather than concurrentOperation given that the default NSOperation main() could execute concurrently with other NSOperation main() code.

Would love to know your thoughts on this

Hey shruti - thanks for your kind words about the video series.

You’re completely correct in that ‘concurrent’ and ‘asynchronous’ are used fairly loosely throughout the video series.

Your description of what happens with a standard NSOperation isn’t quite right. What happens is that NSOperationQueue manages a pool of threads, and when it pops an operation off the queue and begins executing it, the main() method will begin executing but won’t return. It returns when the operation is complete.

In contrast, if you’re using an NSOperation to wrap an asynchronous task, the main() function will necessarily return immediately. In the traditional sense, the state of the operation is dictated by when the main() method returns. This clearly isn’t possible in the async case, hence you have to manage the state yourself.

You are correct in saying that the ConcurrentOperation subclass of NSOperation could also be called AsynchronousOperation.

Hope that clears things up a little :wink:

sam

Hi Sam

Thanks for these nice tutorials. So I am little confused during this video series of NSOperation. In Introducing Concurrency Part 2: NSOperationQueue (11:39) You have shown how opeartion execute concurrently in operation queue but again in other video it is mentioned that all operation are synchronous. Please elaborate it little more conceptually.

Thanks
Rohit Sharma

Hi @rohit0690

This is a little confusing, and sorry for not being able to make it clearer in the video.

In the earlier video, we used an NSOperation to wrap a synchronous function - i.e. one that you call, it performs all its work and then returns once it has completed. Then, you can put a load of these NSOperation subclasses into an NSOperationQueue and they will be executed in a concurrent manner - i.e. they’ll be run at the same time, asynchronously.

In this video we took a look at how you can use an NSOperation subclass to wrap an asynchronous function - i.e. one that returns immediately, performs it’s work in the background and then returns the result via a callback. You have to do some work to be able to wrap these types of functions in an NSOperation, but once you have they can be treated like any other operation. Examples of these asynchronous functions are common in UI updates and networking.

I hope that goes some way to explaining the concepts around this particularly gnarly piece of work.

sam

This is the link to the open source code of the NSOPeration. If we look at start implementation, it calls start() and then an internal function called finish(). This internal function finish() seems to be doing the following:

  • Set self.finished = true
  • Calls _leavegroups() which seems to loop through all the dispatch_groups that the current operation is part of and leave them.
  • Call _queue._operationFinished() on the NSOperationQueue object if it is set in init().
  • Call completionBlock if set

With the override that we have created in this video, it seems like we are not doing the last 3 of the 4 things listed above. So, it seems like we should be careful when using dependencies and completion block with this new AsynchronousOperation that we have defined.

Would love your thoughts on my analysis, if I am missing something

Hi,

I think that the important part from the subclassing notes of NSOperation is the following:

Upon completion or cancellation of its task, your concurrent operation object must generate KVO notifications for both the isExecuting and isFinished key paths to mark the final change of state for your operation.

The internals of NSOperation will ensure that the tidying up all happens on receipt of the KVO notifications of the appropriate properties.

I don’t know a whole lot about the open source Swift implementation - does Swift Foundation include KVO support?

sam

Thanks for the quick response.

Ahh 
 I think this whole misunderstanding stems from me incorrectly assuming that the Open source Swift implementation of NSOperation here is “the” implementation of NSOperation in the Foundation framework that we use when we say “import Foundation” in Xcode.

Here is the swift.org link , under section “Core libraries”, that said that this swift-corelibs-foundation github repository that is said to be ( in the words from the site)

The source code for Foundation, which provides common functionality for all applications.

I also checked my theory is wrong in a playground in the following way:

  • I instantiated an AsynchronousOperation object and sets its completion handler with a debug print statement in it.
  • I called start on this AsynchronousOperation. If my theory is correct, the completion handler should not have been called. But every time, even when the operation is cancelled, I saw that the completion handler’s debug statement is being called as expected.

Thanks for removing me from this confusion that the open sourced repository is the actual “Foundation” framework that we currently use in the Swift iOS projects.

1 Like

Great series so far. But ran into some questions if you don’t mind showing some clarity to them

Question 1
the main() function call (found in start() in ConcurrentOperation) , does it call the override main() function in DataLoadOperation? Is that why the state is equated to .finished in that function code?

Question 2
So when we run the code are there 2 queues running now? For instance, the first Queue when the loadOperation object is added. The main method inside of the function would kick off the async functionality to load the data, a functionality that is added via addOperationWithBlock into a 2nd queue

  1. Technically, yes, we are overriding the main() function, although it’s not an important part of the implementation. I used the main() function to mirror the pattern used for standard NSOperation usage - i.e. representing the function that does the actual work.
  2. You’re correct, there are probably multiple queues going on. You create the queue that manages the execution of the ConcurrentOperations. Each of these uses their own strategy to perform the work in the background - which could involve an NSOperationQueue, or maybe a GCD queue or low-level threads. The purpose of abstracting these asynchronous methods into ConcurrentOperation is that you then don’t need to worry about how they work, and instead have the common NSOperation interface.

Hope that clears things up

sam

1 Like

@shruti hello i am ishan 
i want to learn ios n swift 
but have no money :pensive:
but want to make career in ios 
can anyone tell me how to learn everything
when everything has paid version over here 
i think the videos here are the best but i am having no money to access it :pensive:

Hi @ishan287

raywenderlich.com offers a vast amount of top-quality written content completely for free. We do offer some videos for free, but unfortunately we are unable to make them all for free :frowning:

sam

@samdavies sir please guide me by clearing a point 
 all the written articles which are free here 
does it covers all topic which are in videos?

Hi @ishan287

Not directly no. There are a lot of written articles, and they cover a very wide range of topics. However, the books and videos are more focussed and often go into topics in far more depth.

If you are completely new to iOS, then you can try the iOS Apprentice book:

https://store.raywenderlich.com/products/ios-apprentice

This will teach you everything you need to know from knowing nothing right through to producing high-quality apps. If you sign up to our newsletter then we’ll send you the first part of this book for free:

https://www.raywenderlich.com/newsletter

sam