Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between NSThreads, NSOperations and performSelector

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. 
like image 981
Rajender Kumar Avatar asked Mar 03 '11 04:03

Rajender Kumar


2 Answers

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.

like image 65
Max Avatar answered Sep 22 '22 20:09

Max


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.

like image 38
Kazuki Sakamoto Avatar answered Sep 22 '22 20:09

Kazuki Sakamoto