0

I'm developing an application which must extract new messages for user from the server. I have implemented this as a timer which fires every 2 seconds and call a selector which is a method that implement HTTP request and server respond processing. So I think it is quite a bad idea to do this in a main thread.

I have no experience with multithreading in iOS. So I want to know what fits well for parallelizing of this task: GCD or NSThread?

MainstreamDeveloper00
  • 8,436
  • 15
  • 56
  • 102
  • 1
    Use GCD. I do not want to write again about advantages of GCD over NSThread, but you can search it here and there is lot of information in SO itself – msk Jan 29 '13 at 11:19

1 Answers1

1

You should work as far up the API stack as possible. That way you can concentrate on programming functionality and not managing threads. GCD uses threads that the system has gotten going anyway and its much more efficient than managing your own code. Its even better to aim to encapsulate your networking into NSOperations that can then be put on an NSOperationQueue and these will be executed on one or more background threads, whatever the system deems is a good number for the current power status and other things like that.

The benefit of NSOperation over a pure GCD approach is that operations can be cancelled. Once a block is committed to GCD it has to run no matter what.

If you want to encapsulate your HTTP requests in NSOperations you might be interested to know that someone has already done this for you. AFNetworking is one of the most widely regarded iOS networking stacks and uses NSOperations as its base to build on and as such is very easily multi threaded.

A good idea would be to try and encapsulate your parsing code into an NSOperation and then as your network request operations return you can create parsing operation instances and put them on another queue for processing in the background.

jackslash
  • 8,550
  • 45
  • 56
  • 1
    Note that the "cancel-ability" of NSOperations is of dubious benefit on it's own (i.e. absent explicit, developer-provided code that cooperatively checks for cancellation) -- once an operation has begun executing, it cannot be (meaningfully) cancelled unless it "cancels" itself by returning early. – ipmcc Feb 10 '13 at 17:47