【问题标题】:What is the best way to allocate multiple objects without a crash?在不崩溃的情况下分配多个对象的最佳方法是什么?
【发布时间】:2011-02-14 04:21:03
【问题描述】:

我正在编写一个应用程序,该应用程序从服务器获取图像并将所有图像作为 UIButton 显示给用户,以便我可以拦截其上的事件。问题是,分配所有图像需要很长时间,当它最终显示所有图像时,应用程序在实际设备上崩溃(在模拟器上工作)。

在不崩溃的情况下分配这些图像对象的正确方法是什么?

提前致谢!

这是我当前的代码

 for(start = 1; start <= limit; start++) {

     NSString *tempstring;

     if(start < 10) {
     tempstring = [NSString stringWithFormat:@"0%d", start];
     } else {
     tempstring = [NSString stringWithFormat:@"%d", start];
     }

     NSOperationQueue *queue = [NSOperationQueue new];
     NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(displayThumbs:) object:[NSString stringWithFormat:@"%d", start]];

     [queue addOperation:operation];
     [operation release];
     [queue release];

 }


- (void)displayThumbs:(NSString *)buttoninfo {

        int currentmag = [buttoninfo intValue];
        currentmag--;
        currentmag = (currentmag * 70) + 10;

        NSString *tempstring;
        if([buttoninfo intValue] < 10) {
            tempstring = [NSString stringWithFormat:@"0%@", buttoninfo];
        } else {
            tempstring = [NSString stringWithFormat:@"%@", buttoninfo];
        }   

        UIButton *magbutton = [[UIButton alloc] initWithFrame:CGRectMake(currentmag, 10, 50, 50)];
        magbutton.tag = [buttoninfo intValue];
        [magbutton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_Page_%@.jpg", @"2011-02", tempstring]] forState:UIControlStateNormal];
        [magbutton addTarget:self action:@selector(gotoStory:) forControlEvents:UIControlEventTouchUpInside];
        [thumb_scoller addSubview:magbutton];

        [magbutton release];
        magbutton = nil;

    }

【问题讨论】:

    标签: iphone objective-c ios4 allocation


    【解决方案1】:

    很可能图像比您尝试放入的尺寸大,但是当您一起阅读它们时,它们会占用大量内存。

    在您下载图像时,您应该保存可用于按钮的较小的缩略图版本。

    它在设备上崩溃,因为它对模拟器没有的进程有内存限制。

    【讨论】:

    • 正确!图像的大小从 1680 像素调整为 70 像素。分配 180 多个对象时显然会占用大量内存。谢谢!
    【解决方案2】:

    Kendall Helmstetter Geln 的回答可能会给您带来最好的改进,尽管如果没有看到更多的程序及其执行方式就很难确定。

    除了将图像调整为显示的大小之外,还有一些其他提示:

    • 发布不可见的图像(至少,其中一些)

    • 为您的图像(包括调整大小的图像)使用本地磁盘缓存

    • 尽可能重复使用/共享(内存中)图像

    • 更喜欢创建不自动释放的对象。例如,使用alloc+init+(稍后)release

    • 在创建许多自动释放对象和/或大型自动释放分配的块周围显式创建/销毁自动释放池

    • 配置文件以确定您的分配真正增长的原因/位置。

    • 如果您正在耕种到分配大量的操作队列,也许您应该将其设为串行:[NSOperationQueue setMaxConcurrentOperationCount:1]

    好奇心:为什么每次迭代都创建一个操作队列?

    【讨论】:

    • 我现在把操作队列改成了一个。谢谢!
    • 我什至没有看过 closley 的原始解决方案,但您说得对,某种隐藏不可见图像的解决方案确实是个好主意。特别是这里正在做的事情似乎真的需要使用带有可重复使用单元格的表格,这些单元格会在您滚动时加载到图像中。
    • AQGridView 是一个有趣的项目,可以帮助以更节省内存的方式呈现拇指。
    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多