onsdag 24 augusti 2011

Safe threading!

The importance of threading safely has become clear when working on SC. At many times my background treads has come in touch with UIKIT (Not thread-safe) and crashed. if you e.g.. want to check a value against the server and display different ViewController's depending on the result, you cant't do this on the background thread.

This is my way of doing that (Might be better ways out there):


dispatch_queue_t loginThread = dispatch_queue_create("Login-thread", NULL);
    dispatch_async(loginThread, ^{
    
        NSArray *arrayWithUsernameAndPassword = [NSArray arrayWithObjects:userName, password, nil];
        
    if([dataParser loginOnServer:[self requestActiveServerData] withUsername:userName andPassword:password])
    {
        [self performSelectorOnMainThread:@selector(threadReturnLogin:) withObject:arrayWithUsernameAndPassword waitUntilDone:YES];
    }else
    {
//Should be a rejection here!
    }

    });
    

    dispatch_release(loginThread);
    




     [self performSelectorOnMainThread:@selector(threadReturnLogin:) withObject:arrayWithUsernameAndPassword waitUntilDone:YES];


is the solution to the UIKIT problem. This executes the function on the main thread instead of the custom one!


Happy coding!

Inga kommentarer:

Skicka en kommentar