Invictus
Invictus

Reputation: 33

Running C code in an Objective C (Cocoa) Thread (for iOS)

First of all, I am a a very new Objective C/Cocoa iOS Developer but I've written C/C++ applications before.

So I managed to run the Rabbitmq-c (http://hg.rabbitmq.com/rabbitmq-c/) client inside my iPhone App, and I can connect to Rabbitmq directly from my app and even consume a queue item. So all's good.

Now my problem is, my iPhone app needs to use the rabbitmq-c library to poll for incoming messages in from the server. Probably there will be, an almost infinite while loop.

Do I have to take this to a new thread? Ideally, I want to wrap the rabbitmq-c class as an Async objective C class and use NSNotification (or something similar) to notify my UI. I'm a bit leery of creating a new thread, as I read about stuffs like Runloop etc can solve a lot of problems without using an extra thread.

What is the best way for me to go about this? Any examples of code or directions would be helpful. Please remember, I am not dealing with an Objective C code/Coca rabbitmq library here, I'm using C code inside my iPhone app.

Thanks

Subrat

Upvotes: 3

Views: 1842

Answers (3)

Deepak Keswani
Deepak Keswani

Reputation: 117

Or other way is to write method to receive messages. This method can have infinite loop.

Later you can put this method in background thread like this.

[self performSelectorInBackground:@selector(receiveMessages) withObject:nil];

Upvotes: 0

iHS
iHS

Reputation: 5432

You can also create custom delegates for updating the UI, or the stuff related to UIKit.

Notifications might be a little easier to code and offer the advantage that multiple objects can observe one notification. With delegates, such a thing cannot be done without modifying the delegating object (and is unusual).

Some advantages of delegating:

The connection between delegating object and delegate is made clearer, especially if implementing the delegate is mandatory. If more than one type of message has to be passed from delegatee to delegate, delegating can make this clearer by specifying one delegate method per message.

Upvotes: 0

justin
justin

Reputation: 104698

don't block the main thread with your server polling.

since the operation never ends, create your own thread and run loop for this server polling. you can potentially use the run loop (each thread has one) instead of the infinite while. the alternatives involve regularly spawning threads. it's easiest to just use one thread for this.

once you have an update, post the notification (if you choose NSNotification) from the main thread -- UIKit is meant to operate from the main thread only.

for samples, i'd begin with samples related to NSRunLoop and CFRunLoop.

good luck

Upvotes: 4

Related Questions