加载100个UIImages

时间:2010-07-12 10:19:08

标签: iphone objective-c uiimage asihttprequest

我正忙着使用iPhone应用程序。它的一部分我从Flickr加载100个小图像作为UIButton。 问题是如何处理内存。它每次加载大约5-6 mb。当我通过navigationController popViewController释放视图时,内存几乎保持不变。

我现在所做的是循环所有图像并将请求发送到ASINetworkQueue。当循环准备就绪时,我会[networkQueue go]。

//Loop images
for (NSDictionary* message in output)
{
    NSString *imageURL = [[NSString alloc] initWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_s.jpg", [message objectForKey:@"farm"], [message objectForKey:@"server"], [message objectForKey:@"id"], [message objectForKey:@"secret"]];

    if(cx > 280) { cy = cy + 78; cx = 6.0f; }

    //user data for the request
    NSMutableDictionary *imageInfo = [[NSMutableDictionary alloc] init];

    //init Image
    CGRect myImageRect = CGRectMake(cx, cy, 72.0f, 72.0f);
    UIButton *myImage = [[UIButton alloc] initWithFrame:myImageRect];
    [myImage setTag:i];

    [myImage setBackgroundColor:[UIColor whiteColor]]; //grayColor
    [imageInfo setObject:[NSString stringWithFormat:@"%i", i] forKey:@"arrayNr"];
    [images addObject: myImage];
    [fotoView addSubview: myImage];

    //get url
    NSURL *imageURI = [[NSURL alloc] initWithString:imageURL];

    //load image
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: imageURI];

    [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[message objectForKey:@"id"]]];
    [request setUserInfo: imageInfo];
    [networkQueue addOperation:request];

    [imageURL release];
    [imageURI release];

    [myImage release];
    [imageInfo release];

    cx = cx + 78;
    i++;
}

请求完成后,我这样做:

- (void)imageFetchComplete:(ASIHTTPRequest *)request
{
    UIImage *img = [[UIImage alloc] initWithContentsOfFile:[request downloadDestinationPath]];
    if (img)
    {
        //set image
        UIButton *myButton = [images objectAtIndex:[[[request userInfo] objectForKey:@"arrayNr"] intValue]];
        [myButton setBackgroundImage:img forState: UIControlStateNormal];
        [myButton addTarget:self action:@selector(showImage:) forControlEvents:UIControlEventTouchUpInside];
    }

    [img release];
}

这是我的dealloc功能:

- (void)dealloc
{
    [networkQueue cancelAllOperations];
    networkQueue.delegate = nil;
    [networkQueue release];

    [flickrController cancelAllOperations];
    flickrController.delegate = nil;
    [flickrController release];

    [images release];
    [fotoView release];
    [output release];

    [super dealloc];
}

我不明白记忆不会消失的方式。 解决方案我能想到的是: - 为uibutton / uiimage创建一个自己的对象。 - 使用UITableview处理图像

两种解决方案我都没有看到在关闭视图后如何清除所有内存。 希望有人能够让我了解如何应对这种情况。

1 个答案:

答案 0 :(得分:2)

如果您将代码发布到清理的地方,那么问题出在哪里可能会更清楚,但无论如何我都在猜测:

imageFetchComplete:方法中,当您调用setBackgroundImage:时保留对图像的引用它将保留在内存中,直到您释放保留它的特定按钮对象。由于按钮本身由images数组保留,因此您需要释放此数组,或者在可变数组的情况下从数组中删除该按钮。