user1491987
user1491987

Reputation: 751

How to go back to main run loop of objective C

I'm using a serial cable bought from RedPark(ios device to RS232) for my first project. I already got it to work by sending and receiving data.(Not too far yet.) How I want my app to work is iphone acts as Master in the communication by sending commands and external device reply with the data required.

And lots of times, I need to ask for several data package at a same time.

I ran into a problem that is the readByteAvaible() provided by RedPark, event driven, So I can't send several commands together in viewDidLoad or other methods. I've tried different ways to get all the packages I need. Like multithread. None of them works. From the library FAQ, it's said "you must be returned to your run loop before these are processed".

I'm still fairly new to objective C, and still feel a little confused. Can anyone tell me how to achieve this? Or maybe some information about main run loop of objective C?

Upvotes: 1

Views: 687

Answers (1)

Tommy
Tommy

Reputation: 100662

The run loop is Cocoa's version of an event loop. So it's just a queue of things to do. Objective-C is dynamic so that list tends to be targets and selectors; this isn't like one of the old purely static runtimes like Win32 or the Mac Classic Toolbox where you'd need to wait for a messages struct then enter some elaborate branches based on message type.

Run loops and threads have a one to one relation and the main run loop is that which runs on the main thread.

On the whole, if you put no extra thought into it whatsoever then all of your code will occur on the main run loop because UIKit, which provides all the controls, works only on the main run loop.

So, supposing you had a UIButton and it were wired up to call the didPressButton: then:

- (IBAction)didPressButton:(id)sender
{
    // this code is running on the main run loop

    NSLog(@"I'm executing on the main run loop");

    // when this method ends, control will return to the run loop
}

You probably don't want to multithread, you probably just want to schedule on the run loop.

You can use the performSelectorOnMainThread: methods to schedule something on the main run loop from anywhere. If you're already on the main thread you can just use performSelector:withObject:afterDelay: to schedule something to happen on the main run loop but only after whatever else is already scheduled. You can pass a delay of 0.0 to have it happen next but also give anything else already scheduled to happen next a chance to run.

RedPark's SDK becomes available only once you hand over your email address so I declined to do so; can you give us any more information on exactly how it's formulated? Is it blocks or callbacks or delegates or something else?

Upvotes: 1

Related Questions