views:

284

answers:

4

I have an ai loop that I would like to write for my iphone app. I am under the understanding that this loop will take along time to make calculations and block the main application.

I want to put it in a different thread and run everything off events.

For example I would have an event that would be called when the players turn started. The AI thread would listen to it and react.

What is the best way for my ai thread to communicate with the main thread? I use NSNotificationcenter a lot but I am reading strange stuff like it will not fire the event on the right thread?

What is the best way to communicate through event like actions with threads?

A: 

You can use the methods - performSelectorOnMainThread: to execute a given method on the main thread, and - performSelector:onThread: or - performSelectorInBackground: to execute a method on another thread. Using these methods you can fire events across threads.

Note though, to use - performSelector:onThread: a Run Loop must be running on the target thread, else you method will not be executed.

frenetisch applaudierend
+5  A: 

My recommendation would be to use an NSOperationQueue for your AI processing actions. As the user performs actions, create an NSOperation which handles the AI processing in response of that event and add it to the NSOperationQueue. If there are dependencies between these actions, or if you wish to split your processing up into smaller sub-actions, you can set these actions to process only when certain conditions are met.

Operations placed within an NSOperationQueue will run on a background thread, so they will not block the main thread. For UI updates or other actions that need to be taken on the main thread, I recommend using -performSelectorOnMainThread:withObject:waitUntilDone: to call a method within your operation that posts a notification via NSNotificationCenter's -postNotificationName:object:. Have your view controller or other controller respond to these notifications and do what they need to in response to your AI routine's results.

Brad Larson
A: 

Instead of firing up a seperate thread manually, I would urge you to consider using NSOperation / NSOperationQueue. It is much easier to work with, far less prone to errors and well documented with tutorials and examples all over the web.

Till
lol - see brad's solution, he was about 10secs faster and is far more verbose and descriptive than i am
Till
A: 

I fire the AI in a background thread with performSelectorInBackground and each time the UI needs to be notified about something (the AI resulting action, a progress bar showing the AI working, etc) I use performSelectorOnMainThread:.

Of course, remember to create a NSAutoReleasePool in the background thread.

Marco Mustapic