Search code examples
iosuiimagenskeyedarchiverdata-persistence

UI freeze while saving images


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


Solution

  • 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
    });