这似乎是从 iPhone 扫描图像的经典方法。我有一个从主线程调度的线程去扫描代码。它基本上每次都会创建一个新的 UIImage 然后将其删除。
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
while (![thread isCancelled]) {
#ifdef DEBUG
NSLog(@"Decoding Loop");
#endif
// [self performSelectorOnMainThread:@selector(updateImageBuffer) withObject:nil waitUntilDone:YES];
CGImageRef cgScreen = UIGetScreenImage();
UIImage *uiimage = [UIImage imageWithCGImage:cgScreen];
if (uiimage){
CGSize size = [uiimage size];
CGRect cropRect = CGRectMake(0.0, 80.0, size.width, 360); // Crop to centre of the screen - makes it more robust
#ifdef DEBUG
NSLog(@"picked image size = (%f, %f)", size.width, size.height);
#endif
[decoder decodeImage:uiimage cropRect:cropRect];
}
[uiimage release];
CGImageRelease(cgScreen);
}
}
[pool release];
问题是 [pool release] 导致 ERROR_BAD_EXC (旧经典)和程序炸弹。有人告诉我没有必要调用 [uiimage release],因为我没有明确分配 UIImage,但情况似乎并非如此。如果我去掉那条线,内存使用量就会飙升,程序会因为内存不足而退出。看来我不能按照我想要的方式完成这项工作。
有没有办法“就地”创建 UIImage ?即,是否有一个作为 UIImage 一次又一次写入的缓冲区?我怀疑这会起作用吗?
更新!
尝试在主线程上执行 UIKit 相关调用如下:
-(void)performDecode:(id)arg{
// Perform the decoding in a seperate thread. This should, in theory, bounce back with a
// decoded or not decoded message. We can quit at the end of this thread.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
while (![thread isCancelled]) {
#ifdef DEBUG
NSLog(@"Decoding Loop");
#endif
[self performSelectorOnMainThread:@selector(updateImageBuffer) withObject:nil waitUntilDone:YES];
if (uiimage){
CGSize size = [uiimage size];
CGRect cropRect = CGRectMake(0.0, 80.0, 320, 360); // Crop to centre of the screen - makes it more robust
#ifdef DEBUG
NSLog(@"picked image size = (%f, %f)", size.width, size.height);
#endif
[decoder decodeImage:uiimage cropRect:cropRect];
}
}
}
[pool drain];
#ifdef DEBUG
NSLog(@"finished decoding.");
#endif
}
-(void) updateImageBuffer {
CGImageRef cgScreen = UIGetScreenImage();
uiimage = [UIImage imageWithCGImage:cgScreen];
//[uiimage release];
CGImageRelease(cgScreen);
}
然而,当人们希望抓住 UIImage 的“大小”时,EXC_BAD_ACCESS 抬起了丑陋的脑袋,这并不令人高兴