SirRoot
SirRoot

Reputation: 259

iPhone MultiThreading: List/Queue

I finally got my telnet iPhone application running to send text commands to a device i'm working on but the device isn't as fast as i would like it to be.

As of now when i press a button the phone sends a text command to the device's IP. I want to change it so that a constant process is running and checking a queue every .25 seconds. If the queue has any elements it will send, wait .25 seconds, and check again.

My initial guess is that I should check some iPhone threading libraries so that the buttons that add to queue and the send/checker method could be in separate threads.

I was looking at iOS Reference specifically at the Operation Queue and Dispatch Queue. Are these queues what I should be looking at or am i completely off here?

UPDATE:

I think i found what I want in NSThread however im reading NSMutableArray isnt thread safe. Is there a list type queue or vector that is thread safe in objective c?

UPDATE 2:

Could I use a mutablearray and put a lock{} around it everytime i add or remove objects?

Upvotes: 2

Views: 331

Answers (3)

Dan Ray
Dan Ray

Reputation: 21903

Why not fire the command immediately via an asynchronous method?

Letting the framework handle the multithreading is almost always the right idea, in my experience.

Upvotes: 0

Marcelo Alves
Marcelo Alves

Reputation: 1846

GCD would be a better solution, NSTimers are not really that good for periodic tasks. Check the dispatch_after documentation.

Upvotes: 0

Cameron Spickert
Cameron Spickert

Reputation: 5200

You're on the right track. Running a task at a regular time interval sounds like a job for NSTimer. To get this behavior, try creating a timer like so:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(doTask) userInfo:nil repeats:YES];

Set this object to an instance variable and it will run -doTask every 0.25 seconds. As for your background operations, NSOperation and NSOperationQueue are probably your best bets. Create a custom NSOperation subclass and override the appropriate methods to run a task in the background.

Upvotes: 1

Related Questions