1

I'm trying to save a NSDictionary containing 30 images. I'm calling the method to save the dictionary in the viewDidDisappear of my ViewController. The problem is that the UI freeze while saving. It's a small lag, less than a second, but a bit annoying. Do you have any ideas to make it more fluid? Maybe I should save the dictionary asynchronously, maybe in a block, but I don't know well how to use them.

Here's my saving et getting methods :

+ (NSDictionary*)getProgramImages{
    NSString *path = [DataManager getProgramImagesFileDirectory];
    NSDictionary *programImages = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

    return programImages;
}

+ (void)saveProgramImages:(NSDictionary*)programImages{
    NSString *path = [DataManager getProgramImagesFileDirectory];

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:programImages];
    [data writeToFile:path options:NSDataWritingAtomic error:nil];
}

Thanks a lot for your help!

Boris

Boris88
  • 297
  • 2
  • 14
  • The issue is that you're calling the save functions on the main thread, which freezes the UI if its too heavy. Read more about threads here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html – Milo Jun 13 '14 at 02:31

3 Answers3

2

You could try wrapping your function call using the below code, which uses Grand Central Dispatch to run that code on a background thread. Not able to test at the moment to see if that could solve your issue or not.

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // call that function inside here
});
Mike
  • 9,765
  • 5
  • 34
  • 59
1

Maybe dispatch_async could help you to smoothen the code running on main thread.

 dispatch_async(dispatch_get_main_queue(),^{
        //your code goes here
    });
HelmiB
  • 12,303
  • 5
  • 41
  • 68
1

There're many ways to solve your problem. You should read this Concurrency Programming

Grand Central Dispatch is a good choice.

Quang Hà
  • 4,613
  • 3
  • 24
  • 40