London
London

Reputation: 15274

Improving code execution speed

I'm having some issues with my code and not sure how to speed things up. Here is my code from app delegate (didFinishLaunchingWithOptions method body):

initialized = [[NSUserDefaults standardUserDefaults] boolForKey:@"initialized"];

if (!initialized) {
     dispatch_queue_t queue = dispatch_get_global_queue(
                                                       DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);


    dispatch_async(queue, ^{
        [DAO setDocumentsCacheDirectory:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];

        ....download images and files needed by application

        NSLog(@"%@", @"Finished downloadding images and files");

        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" object:nil];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"initialized"];
    });
}

While this asynchronous download is happening I have spinning gif image in my view. As you can see when all this download is done the refreshView method is triggered in my view controller.

After load has finished re-loading I have NSLog(@"%@", @"Finished reloading.."); so I know when the view has re-loaded.

The problem :

So I'm looking at the console :

2012-06-07 12:52:34.898 TestApp[29800:13c03] Finished downloadding images and files
[Switching to process 29800 thread 0x13c03]
2012-06-07 12:52:34.909 TestApp[29800:13c03] Finished reloading..

File download appears to be done within second or two. Then immediately after as you can see by the timestamp the view reload finishes.

But thing is application waits for 5 seconds or so and I have no idea where and what is going on and only then the view re-refreshes although the message finished reloading.. was displayed about 5 seconds ago.

What would you do next?

Upvotes: 1

Views: 197

Answers (1)

Ashley Mills
Ashley Mills

Reputation: 53141

You're posting the notification in the background queue - if this is what triggers the UI update then this needs to be done on the main queue:

dispatch_async(queue, ^{
    [DAO setDocumentsCacheDirectory:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];

    ....download images and files needed by application

    NSLog(@"%@", @"Finished downloadding images and files");

    dispatch_sync(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" object:nil];
    }

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"initialized"];
});

Notice I've used dispatch_sync here... the NSUserDefaults won't be updated until the main queue block completes.

Upvotes: 5

Related Questions