简体   繁体   中英

Problem with UIImageView loading via OperationQueue

I load a UIImageView using an NSOperationQueue.

The load fetches an image from the Internet and then adds it to an image view. The problem I have is that the method finishes but it takes about 3 seconds later for the image view to actually either show the image or remove the image view from the superview...

- (void)viewDidLoad { NSLog(@"AirportDetailView: viewDidLoad");
    [super viewDidLoad];
    [self.activity startAnimating];
    self.queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:NULL]; 
    [self.queue addOperation:operation]; 
    [operation release];
}

-(void)loadImage {
        [myAp ImageForAp];

        NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram);

        [self.activity stopAnimating];

        if (myAp.ApDiagram==NULL) {
            NSLog(@"Finally Gets Here");
            [self.Diagram removeFromSuperview];
        }
        else {
            NSLog(@"Finally Gets Here with Diag");
            [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
        }

    }

The NSLOG shows a delay between the first two log statements of about 3 seconds can't understand why....

Updated with my Latest Code......

-(void)loadImage {

    [myAp ImageForAp];

    NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram);

    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO];
}

-(void)UpdateUI {

    [self.activity stopAnimating];

    if (myAp.ApDiagram==NULL) {
        NSLog(@"Finally Gets Here");
        [self.Diagram removeFromSuperview];
    }
    else {
        NSLog(@"Finally Gets Here with Diag");
        [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
    }
}

Make sure that the loadImage method is being run on the main thread. All UI operations need to happen on the main thread to work as expected. Your code will need to look similar to this.

-(void)loadImage {
    [myAp ImageForAp];
    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO];
}

-(void)UpdateUI {
    [self.activity stopAnimating];

    if (myAp.ApDiagram==NULL) {
        [self.Diagram removeFromSuperview];
    }
    else {
        [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
    }
}

There is also a possible memory leak inside of viewDidLoad.

self.queue = [NSOperationQueue new]; should be changed to

self.queue = [[[NSOperationQueue alloc] init] autorelease];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM