6.18. Exiting Threads and Timers
Problem
You would like to stop a thread or a timer, or prevent one from firing again.
Solution
For timers, use the invalidate
instance method of NSTimer
. For
threads, use the cancel
method. Avoid
using the exit
method of threads, as
it does not give the thread a chance to clean up after itself and your
application will end up leaking resources:
NSThread
*
thread
=
/* Get the reference to your thread here */
;
[
thread
cancel
];
NSTimer
*
timer
=
/* Get the reference to your timer here */
;
[
timer
invalidate
];
Discussion
Exiting a timer is quite straightforward; you can simply call the timer’s invalidate
instance method. After you call
that method, the timer will not fire any more events to its target
object.
However, threads are a bit more complicated to exit. When a thread
is sleeping and its cancel
method is
called, the thread’s loop will still perform its task fully before
exiting. Let me demonstrate this for you:
-
(
void
)
threadEntryPoint
{
@
autoreleasepool
{
NSLog
(
@"Thread Entry Point"
);
while
([[
NSThread
currentThread
]
isCancelled
]
==
NO
){
[
NSThread
sleepForTimeInterval:
4
];
NSLog
(
@"Thread Loop"
);
}
NSLog
(
@"Thread Finished"
);
}
}
-
(
void
)
stopThread
{
NSLog
(
@"Cancelling the Thread"
);
[
self
.
myThread
cancel
];
NSLog
(
@"Releasing the thread"
);
self
.
myThread
=
nil
;
}
-
(
BOOL
)
application:
(
UIApplication
*
)
application
didFinishLaunchingWithOptions:
(
NSDictionary
*
)
launchOptions
{
self
.
myThread
=
[[
NSThread
alloc
]
initWithTarget:
self
selector:
@selector
(
threadEntryPoint ...
Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.