Zeus
Zeus

Reputation: 571

Sleep for NSThread

I'm trying to use sleep in the below code when the NSStream Connection fails or if there's a Stream Error and tries to reconnect after sleep. The Sleep is working but it puts the Whole Application to Sleep.

I have started NSStream as a Thread, but when the NSStreamEvent is received, the handleEvent seems to be working as a Synchronous method.

Any ideas on using Sleep for this piece of Code ..? I just want the sleep to work for the Stream Thread alone.

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event 
{
        case NSStreamEventErrorOccurred:
        {
            NSError *streamErr = [stream streamError];
            NSString *strErr = [streamErr localizedFailureReason];
            [self CloseStream];
            NSLog(@"Stream Error ::: %@",strErr);
            //[NSThread sleepForTimeInterval : 15];
            sleep(15);
            [self Initialize];
            [self OpenStream];
            break;
        }

        case NSStreamEventEndEncountered:
        {
            NSLog(@"Connection Closed by the Server");
            [self CloseStream];
            usleep(15000);
            [self Initialize];
            [self OpenStream];
            break;
        }
}

Upvotes: 1

Views: 1119

Answers (1)

Marco
Marco

Reputation: 1306

You should use GCD (Grand Central Dispatch). Your code is being executed in the Background and your application doesn't freeze.

Read this: GCD Reference

Basically you create a queue and add a block of code, which is being executed in the background. Here's my code example

dispatch_queue_t backgroundQueue = dispatch_queue_create("some_identifier", NULL);
dispatch_async(backgroundQueue, ^(void) {   
        //do your background stuff

        dispatch_sync(dispatch_get_main_queue(), ^{
            //update the gui (if needed)
        });

    });

Upvotes: 1

Related Questions