dataWithContentsOfURL and imageWithData take 84% o

2019-07-30 12:10发布

问题:

these two lines took 40% and 42% (together 84%) of the whole loading time of my app. I tested it with Instruments.

NSData *storeImageData = [NSData dataWithContentsOfURL:storeImageURL]; //40% whole load time
UIImage *storeImage = [UIImage imageWithData:storeImageData]; //42% whole load time 

Is there another / better way to speed up the loading time of my app? These two lines and a lot more code are in a loop wich will loop about 500 times.

Note
after adding "http://" to the usual "www.blah.net" it starts to be slow. Does anyone know why 7 characters (of about 30-50) in an URL slows the loading time so massively down. Before I changed it, it took 3 seconds. Now 37 seconds.

回答1:

Replace your lines with these,

 __block NSData *storeImageData;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, NULL);
dispatch_async(queue, ^{
    //load url image into NSData
    storeImageData = [NSData dataWithContentsOfURL:storeImageURL];

    dispatch_sync(dispatch_get_main_queue(), ^{
        //convert data into image after completion
        UIImage *storeImage = [UIImage imageWithData:storeImageData];
        //do what you want to do with your image
    });

});
dispatch_release(queue);

For further info, see dispatch_queue_t