Difference between revisions of "MoPhO/iPhoneDevelopment"

From CCRMA Wiki
Jump to: navigation, search
(Created page with '= Code snippets = === Update view from a different thread (not the main thread) === If you have a function that runs on a different thread and you want to update something in a…')
 
(Code snippets)
 
Line 1: Line 1:
 
= Code snippets =
 
= Code snippets =
 +
 +
'''Pleas add any snippet of code that you think might be helpful to others.'''
 +
  
 
=== Update view from a different thread (not the main thread) ===
 
=== Update view from a different thread (not the main thread) ===

Latest revision as of 13:33, 12 November 2009

Code snippets

Pleas add any snippet of code that you think might be helpful to others.


Update view from a different thread (not the main thread)

If you have a function that runs on a different thread and you want to update something in a View, you will need to add a NSAutoreleasePool to that thread (or at least the function) and then you need to call the performSelectorOnMainThread method on the view or object you are updating.

For example, assuming that data is a pointer to a UILabel in the view that we want to update in the callback:

// Function not running in the Main Thread 
void callback( void * data )
{
    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
    UILabel * me = (UILabel *)data;
    [me performSelectorOnMainThread:@selector(setText:) withObject:@"New text" waitUntilDone:YES];
    [autoreleasepool release];
}

Instead of a UILabel you can pass any other widget.