How can I call the method again without blocking the interface?

A pretty general question, is there a way to call the method that I do so often with the application without blocking the loading of the user interface?

+3
source share
5 answers

You can use Grand Central Dispatch for this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{
    // Call your method.
});
+7
source

You really want to use Grand Central Dispatch for this, but I would like to note that GCD has a method of building only for this kind of thing, it dispatch_apply()executes its block a certain number of times in the queue of your choice, of course, tracking what iteration you are on this way . Here is an example:

size_t iterations = 10;

dispatch_queue_t queue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);

dispatch_apply(iterations, queue, ^(size_t i) {
    NSLog(@"%zu",i);// Off the main thread.

    dispatch_async(dispatch_get_main_queue(), ^{
        // Go back to main queue for UI updates and such
    });
});
+5

:

[self performSelectorInBackground:@selector(aMethod) withObject:nil];

. -

[self performSelectorInBackground:@selector(otherMethodWithString:andData:) withObjects:string, data, nil];

.

+1

, , .

- (void)method
{
    // start a background proccess that will not block the UI
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        for (int i = 0; i < 1000000; i++) {

            if (i == 999) {

                // Need to iterate with interface elements when inside a background thread.
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Found" message:@"Found your number" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alertView show];
                });
            }

            NSLog(@"Count: %d",i);
        }

    });
}
+1

GCD - , , , .

, , (, -), NSOperation isCancelled.

(AFNetworking (, AFHTTPRequestOperationManager) / -.)

Apple NSOperation, Ray Wenderlich NSOperation s.

+1

All Articles