6.17. Invoking Background Methods
Problem
You want to know an easy way to create threads without having to deal with threads directly.
Solution
Use the performSelectorInBackground:withObject:
instance method of NSObject
:
-
(
BOOL
)
application:
(
UIApplication
*
)
application
didFinishLaunchingWithOptions:
(
NSDictionary
*
)
launchOptions
{
[
self
performSelectorInBackground:
@selector
(
firstCounter
)
withObject:
nil
];
[
self
performSelectorInBackground:
@selector
(
secondCounter
)
withObject:
nil
];
[
self
performSelectorInBackground:
@selector
(
thirdCounter
)
withObject:
nil
];
self
.
window
=
[[
UIWindow
alloc
]
initWithFrame:
[[
UIScreen
mainScreen
]
bounds
]];
self
.
window
.
backgroundColor
=
[
UIColor
whiteColor
];
[
self
.
window
makeKeyAndVisible
];
return
YES
;
}
The counter methods are implemented in this way:
-
(
void
)
firstCounter
{
@
autoreleasepool
{
NSUInteger
counter
=
0
;
for
(
counter
=
0
;
counter
<
1000
;
counter
++
){
NSLog
(
@"First Counter = %lu"
,
(
unsigned
long
)
counter
);
}
}
}
-
(
void
)
secondCounter
{
@
autoreleasepool
{
NSUInteger
counter
=
0
;
for
(
counter
=
0
;
counter
<
1000
;
counter
++
){
NSLog
(
@"Second Counter = %lu"
,
(
unsigned
long
)
counter
);
}
}
}
-
(
void
)
thirdCounter
{
@
autoreleasepool
{
NSUInteger
counter
=
0
;
for
(
counter
=
0
;
counter
<
1000
;
counter
++
){
NSLog
(
@"Third Counter = %lu"
,
(
unsigned
long
)
counter
);
}
}
}
Discussion
The performSelectorInBackground:withObject:
method
creates a new thread in the background for us. This is equivalent to the creating a new thread for the selectors. The most important thing we ...
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.