4. Nikmesoft Ltd
Overview
When an application is launched, the system creates a
thread of execution for the application, called "main."
The main thread is also sometimes called the UI
thread.
The system does not create a separate thread for each
instance of a component. All components that run in
the same process are instantiated in the UI thread,
and system calls to each component are dispatched
from that thread.
4
5. Nikmesoft Ltd
Overview
If everything is happening in the UI thread,
performing long operations such as network access or
database queries will block the whole UI.
When the thread is blocked, no events can be
dispatched, including drawing events.
5
6. Nikmesoft Ltd
Overview
Even worse, if the UI thread is blocked for more than a
few seconds (about 5 seconds currently) the user is
presented with the infamous "application not
responding" (ANR) dialog (Android)
6
7. Nikmesoft Ltd
Overview
The user might then decide to quit your application
and uninstall it if they are unhappy.
7
8. Nikmesoft Ltd
Overview
There are simply two rules to single thread model:
Do not block the UI thread
Do not access the UI toolkit from outside the UI thread
8
9. Nikmesoft Ltd
Overview
Having multiple threads in an application provides two
very important potential advantages:
Multiple threads can improve an application’s perceived
responsiveness.
Multiple threads can improve an application’s real-time
performance on multicore systems.
9
11. Nikmesoft Ltd
NSThread & NSRunloop
Create new Thread
[NSThread detachNewThreadSelector:@selector(startTheBackgro
undJob) toTarget:self withObject:nil];
Create subclass of NSThread and override main method
Run on UI Thread
[self performSelectorOnMainThread:@selector(updateUI) withObj
ect:nil waitUntilDone:NO];
11
12. Nikmesoft Ltd
NSThread & NSRunloop
The problem
Touches aren’t the only source of input to an
iPhone application. Ex socket listening
But you don’t want the UI to lock up whilst it’s
listening – you still want input from the user to be
dealt with promptly.
Similarly, you might want events to be triggered
automatically at certain time intervals, but without
locking up the application in the interim.
12
14. Nikmesoft Ltd
NSThread & NSRunloop
NSRunLoop
A run loop is an abstraction that (among other things) provides a
mechanism to handle system input sources (sockets, ports, files,
keyboard, mouse, timers, etc).
Each NSThread has its own run loop, which can be accessedvia
the currentRunLoop method.
A run loop for a given thread will wait until one or more of its input
sources has some data or event, then fire the appropriate input
handler(s) to process each input source that is "ready.".
14
15. Nikmesoft Ltd
NSThread & NSRunloop
NSRunLoop
After doing so, it will then return to its loop, processing input from
various sources, and "sleeping" if there is no work to do.
15
16. Nikmesoft Ltd
NSThread & NSRunloop
16
Design Tips
Avoid Creating Threads Explicitly
Keep Your Threads Reasonably Busy
Avoid Shared Data Structures
Terminate Your Threads Cleanly
19. Nikmesoft Ltd
Blocks
Blocks
Blocks are Objective-C’s anonymous functions.
Function and function pointer
Creating Blocks
Blocks use all the same mechanics as normal functions. You can
declare a block variable just like you would declare a function,
define the block as though you would implement a function, and
then call the block as if it were a function:
19
21. Nikmesoft Ltd
Blocks
Blocks as Method Parameters
Storing blocks in variables is occasionally useful, but in the real
world, they’re more likely to be used as method parameters. They
solve the same problem as function pointers, but the fact that they
can be defined inline makes the resulting code much easier to
read.
21
23. Nikmesoft Ltd
Blocks
Defining Block Types
Storing blocks in variables is occasionally useful, but in the real
world, they’re more likely to be used as method parameters. They
solve the same problem as function pointers, but the fact that they
can be defined inline makes the resulting code much easier to
read.
23
30. Nikmesoft Ltd
NotificationCenter
Delegation
Pros
• Ability to have multiple protocols defined one controller, each with different
delegates.
• No third party object required to maintain / monitor the communication
process.
• Ability to receive a returned value from a called protocol method. This means
that a delegate can help provide information back to a controller
30
31. Nikmesoft Ltd
NotificationCenter
Delegation
Pros
• Very strict syntax. All events to be heard are clearly defined in the delegate
protocol.
• Compile time Warnings / Errors if a method is not implemented as it should be
by a delegate.
• Protocol defined within the scope of the controller only.
• Very traceable, and easy to identify flow of control within an application.
31
32. Nikmesoft Ltd
NotificationCenter
Delegation
Cons
• Many lines of code required to define: 1. the protocol definition, 2. the delegate
property in the controller, and 3. the implementation of the delegate method
definitions within the delegate itself.
• Although possible, it can be difficult and the pattern does not really lend itself
to have multiple delegates of the same protocol in a controller (telling multiple
objects about the same event)
32
33. Nikmesoft Ltd
NotificationCenter
NotificationCenter
Pros
• Easy to implement, with not many lines of code.
• Can easily have multiple objects reacting to the same notification being
posted.
• Controller can pass in a context (dictionary) object with custom information
(userInfo) related to the notification being posted.
33
34. Nikmesoft Ltd
NotificationCenter
NotificationCenter
Cons
• No compile time to checks to ensure that notifications are correctly handled by
observers.
• Required to un-register with the notification center if your previously registered
object is deallocated.
• Not very traceable. Attempting to debug issues related to application flow and
control can be very difficult.
34
35. Nikmesoft Ltd
NotificationCenter
NotificationCenter
Cons
• Third party object required to manage the link between controllers and
observer objects.
• Notification Names, and UserInfo dictionary keys need to be known by both
the observers and the controllers. If these are not defined in a common place,
they can very easily become out of sync.
• No ability for the controller to get any information back from an observer after
a notification is posted.
35
39. Nikmesoft Ltd
GCD & NSOperations
GCD
Grand Central Dispatch, or GCD for short, is a C API that makes it
exceptionally easy to perform asynchronous operations in iOS.
With GCD, you can line up blocks of code in a queue for the
system to execute as necessary. These blocks or operations, will
be dispatched in the queue to another thread, leaving your main
UI thread to continue its tasks.
39
40. Nikmesoft Ltd
GCD & NSOperations
Queues
40
Serial
queue
Concurrent
queue
main
queue
global
queue
User
queue
51. Nikmesoft Ltd
GCD & NSOperations
NSOperations
GCD is a lightweight way to represent units of work that are going
to be executed concurrently. You don’t schedule these units of
work; the system takes care of scheduling for you. Adding
dependency among blocks can be a headache. Canceling or
suspending a block creates extra work for you as a developer!
51
52. Nikmesoft Ltd
GCD & NSOperations
NSOperations
NSOperation and NSOperationQueue add a little extra overhead
compared to GCD, but you can add dependency among various
operations. You can re-use operations, cancel or suspend them.
52
53. Nikmesoft Ltd
GCD & NSOperations
Create a NSOperation
Subclass NSOperation
Override “main”
Create an “autoreleasepool” in “main”
Put your code within the “autoreleasepool”
53
55. Nikmesoft Ltd
GCD & NSOperations
Important notes
Dependency: you can make an operation dependent on other
operations. Any operation can be dependent on any number of
operations. When you make operation A dependent on operation
B, even though you call “start” on operation A, it will not start
unless operation B isFinished is true.
55
56. Nikmesoft Ltd
GCD & NSOperations
Important notes
Priority: sometimes the operation you wish to run in the
background is not crucial and can be performed at a lower priority.
You set the priority of an operation by using “setQueuePriority:”.
Completion block: another useful method in NSOperation class
is setCompletionBlock:. If there is something that you want to do
once the operation has been completed, you can put it in a block
and pass it into this method. Note that there is no guarantee the
block will be executed on the main thread.
56
57. Nikmesoft Ltd
GCD & NSOperations
Important notes
Always check for the isCancelled property frequently. You don’t
want to run a operation in the background if it is no longer
required!
You cannot reuse an operation. Once it is added to a queue, you
give up ownership. If you want to use the same operation class
again, you must create a new instance.
A finished operation cannot be restarted.
57
58. Nikmesoft Ltd
GCD & NSOperations
Important notes
If you cancel an operation, it will not happen instantly. It will
happen at some point in the future when someone explicitly
checks for isCancelled == YES in “main”; otherwise, the operation
will run until it is done.
58
59. Nikmesoft Ltd
GCD & NSOperations
NSOperationQueue
Concurrent operations
Maximum number of concurrent operations: you can set the
maximum number of operations that NSOperationQueue can run
concurrently. NSOperationQueue may choose to run any number
of concurrent operations, but it won’t be more than the maximum.
Add operation
Pending operations:
59
60. Nikmesoft Ltd
GCD & NSOperations
NSOperationQueue
Pending operations: at any time you can ask a queue which
operations are in the queue, and how many operations there are
in total. Remember that only those operations that are waiting to
be executed, and those that are running, are kept in the queue. As
soon as an operation is done, it is gone from the queue.
60
61. Nikmesoft Ltd
GCD & NSOperations
NSOperationQueue
Pause (suspend) queue: you can pause a queue by setting
setSuspended:YES. This will suspend all operations in a queue —
you can’t suspend operations individually. To resume the queue,
simply setSuspended:NO.
Cancel operations: to cancel all operations in a queue, you
simply call “cancelAllOperations”. Do you remember earlier where
it was noted that your code should frequently check for
isCancelled property in NSOperation?
61
62. Nikmesoft Ltd
GCD & NSOperations
NSOperationQueue
addOperationWithBlock: if you have a simple operation that
does not need to be subclasses, you can simply pass it into a
queue by way of a block.
[NSOperationQueuemainQueue]:
NSInvocationOperation is a subclass of NSOperation which
allows you to specify a target and selector that will run as an
operation.
62