How to return an UIImage type from a GCD

2019-08-28 20:40发布

问题:

I have an "UIImage" return type method named "ComLog". I want to return a Image from this method. In "ComLog" method i use GCD to get the image value from an array. I use the following code, the "NSLog(@"qqqqqqqqqqq %@", exiIco)" print the 'image' value but NSLog(@"qqqqqqqqqqq %@", exiIco);" don't. Here is the details :

-(UIImage*) ComLog
{
ExibitorInfo *currentExibitor100 = [[ExibitorInfo alloc] init];
currentExibitor100 = [self.exibitorsArray objectAtIndex:0];

imageQueueCompanyLogo = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(imageQueueCompanyLogo, ^
{
    UIImage *imageCompanyLogo = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentExibitor100 companyLogoURL]]]];
    dispatch_async(dispatch_get_main_queue(), ^
    {
        self.exibitorIcoImageView.image = imageCompanyLogo;
        exiIco = imageCompanyLogo;
        NSLog(@"qqqqqqqqqqq %@", exiIco);
    });
});
return exiIco;
}


- (void)viewDidLoad
{
   [super viewDidLoad];
   UIImage *a = [self ComLog];
   NSLog(@"It should be a image %@", a);
}

Here all the properties are declared globally(In "Myclass.h" file). I am new in Objective C. Please give reply if you know the answer. Thanks in Advance.

回答1:

First of all, I would recommend you to read about blocks in Objective C. The dispatch_async block you are using inside your function is async and thus it returns immediately after you use it, as it runs in it's own pool. For proper use, you can call another method to return the image processes inside the block, or post NSNotification when your image is ready. like this:

-(void) ComLog
{
    ExibitorInfo *currentExibitor100 = [[ExibitorInfo alloc] init];
    currentExibitor100 = [self.exibitorsArray objectAtIndex:0];

    imageQueueCompanyLogo = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(imageQueueCompanyLogo, ^
    {
        UIImage *imageCompanyLogo = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentExibitor100 companyLogoURL]]]];
        dispatch_async(dispatch_get_main_queue(), ^
                       {
                           self.exibitorIcoImageView.image = imageCompanyLogo;
                           exiIco = imageCompanyLogo;
                           NSLog(@"qqqqqqqqqqq %@", exiIco);
                           [self imageIsReady:exiIco];
                       });
    });
//    return exiIco;
}

- (void)imageIsReady:(uiimage *)image
{
    //do whatever you want with the image
    NSLog(@"Image is here %@", image);
}


回答2:

There's so much wrong in your code snippet that it is difficult to decide where to start.

I would suggest to leave GCD for now, and take a look at it later when you are more experienced.

Basically, you want to load an image from a remote server. NSURLConnection provides a convenient method for this which is sufficient for very simple use cases:

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler;

You can find the docs here: NSURLConnection Class Reference.

The recommended approach to load remote resources is using NSURLConnection in asynchronous mode implementing the delegates. You can find more info here: URL Loading System Programming Guide - Using NSURL Connection

I would also recommend to read Conventions.

Here is a short example how to use sendAsynchronousRequest:

NSURL* url = [NSURL URLWithString:[currentExibitor100 companyLogoURL]];
NSMutableURLRequest* urlRequest = [NSURLRequest requestWithURL:url];     
NSOperationQueue* queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest 
                                   queue:queue    
                       completionHandler:^(NSURLResponse* response, 
                                                  NSData* data, 
                                                 NSError* error)
{
    if (data) {        
        // check status code, and optionally MIME type
        if ( [(NSHTTPURLResponse*)(response) statusCode] == 200 /* OK */) {
            UIImage* image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.exibitorIcoImageView.image = image;
                });
            } else {
                NSError* err = [NSError errorWithDomain: ...];
                [self handleError:err];  // execute on main thread!
            }                
        }
        else {
             // status code indicates error, or didn't receive type of data requested
             NSError* err = [NSError errorWithDomain:...];
             [self handleError:err];  // execute on main thread!
        }                     
    }
    else {
        // request failed - error contains info about the failure
        [self handleError:error]; // execute on main thread!
    }        
}];