NSOperationQueue调用performSelectorOnMainThread使应用程序崩溃

时间:2013-02-26 02:05:54

标签: multithreading memory crash nsthread

我正在使用以下代码从服务器下载一些图片,

-(void)viewDidLoad
{
     for (int i = 0 ; i < picsNames.count ; i++) {

         UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(i * 320.0, 0.0, 320.0, self.view.frame.size.height)];
         imageView.backgroundColor = [UIColor blackColor];
         imageView.tag = IMAGE_VIEWS_TAG + i;

         [scrollView addSubview:imageView];

         //getting the image
         NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(getImage:) object:imageView];
         [queue addOperation:operation];
     }
}


-(void)getImage:(UIImageView *)imageView
{
     //getting the "image" from the server .....
     [self performSelectorOnMainThread:@selector(loadPic:) withObject:[NSArray arrayWithObjects:imageView, image,nil] waitUntilDone:YES];
}

-(void)loadPic:(NSArray *)imageAndImageViewArray
{
    //loading the image to imageview
    UIImageView *imageView = (UIImageView *)[imageAndImageViewArray objectAtIndex:0];
    imageView.image = (UIImage *)[imageAndImageViewArray objectAtIndex:1];
}

加载一些图片后,以下行会显示内存警告并导致应用崩溃。

[self performSelectorOnMainThread:@selector(loadPic:) withObject:[NSArray arrayWithObjects:imageView, image,nil] waitUntilDone:YES];

我不知道如何解决这个问题。 谢谢大家:)

1 个答案:

答案 0 :(得分:0)

因此,在花了太多时间之后,我意识到错误是由于太多的UIImage对象分配同时没有主NSTread的NSQueue。

所以只需更改为代码,这样我当时只有10个UIImage对象。