I want to ask some simple but important questions regarding iPhone development. If we have to perform tasks in the background and when the background tasks are completed we will update the UI, for this we can use NSThreads, NSOperations or (performSelector)performSelectorInBackgroundThread. What is the difference between all these and how they will effect my apps performance.
One more thing, what is the difference between these two statements written bellow:-
[self getData];
[self performSelector:@selector(getData)];
Please explain as i dont know the difference between all these things.
There is actual not a big difference between
[self getData];
AND
[self performSelector:@selector(getData)];
The only difference is when you call [self getData] the compiler can determine that you want to send getData message to the object of class [self class]
. And if it can't find any method prototypes, that were declared earlier there would be a warning.
The first and the second lines would be translated to
objc_msgsend(self, _cmd)
performSelector:
is really cool thing when you want to do something at runtime (for example you determine at runtime what exact message you want to send to the object). Or here is an example from the "real life": UIButton has method
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
So it stores the action somewhere in it's internals and when there is appropriate control event it calls:
[target performSelector: action];
NSOperation is just a nice way to wrap your work with threads. And NSThread is just wrapper to pthreads.
So your app performance doesn't really depend on the way you're using threads, however it's much easier to do that using NSOperation rather than pthreads.
NSThread is wrapper for pthreads (POSIX threads). pthreads is implemented atop of Mach thread. You can set stack size, priority when you are using NSThread. (By the way, as far as my experience, stack size doesn't affect at all.)
NSOperation/NSOperationQueue is wrapper for Grand Central Dispatch (libdispatch) aka GCD. GCD is implemented atop of pthreads. These are more easily to use than NSThread for many tasks. It reduces boilerplate code for task queueing, thread pool managing and so forth.
performSelectorInBackground: invokes NSThread and treats terminated NSThread. It is the easiest to use in these for only one method invoking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With