我正在编写一个从服务器获取图像的应用程序,并将所有图像作为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;
}
答案 0 :(得分:1)
很可能这些图像大于你试图放入它们的尺寸,但是当你一起阅读它们时它们占用了大量的内存。
在下载图像时,您应该保存较小的缩略图版本,这些缩略图版本可用于按钮。
它在设备上崩溃,因为它对模拟器没有的进程有内存限制。
答案 1 :(得分:1)
Kendall Helmstetter Geln的回答可能会给你最好的单一改进,虽然很难确定没有看到更多的程序,以及它是如何执行的。
除了将图像大小调整为显示尺寸外,还有其他一些提示:
发布不可见的图像(至少是其中一些图像)
为您的图片使用本地磁盘缓存(包括已调整大小的图片)
尽可能重用/共享(内存中)图像
更喜欢创建未自动释放的对象。例如,使用alloc
+ init
+(稍后)release
在创建许多自动释放对象和/或大量自动释放分配的块周围显式创建/销毁自动释放池
个人资料,用于确定您的分配真正增长的原因/位置。
如果你正在分配一个分配很多的操作队列,也许你应该把它变成序列:[NSOperationQueue setMaxConcurrentOperationCount:1]
好奇心:为什么每次迭代创建一个操作队列?