我正在加载应用程序后将图像延迟加载到数组中。我尝试过使用 NSMutableArray 和 NSArray(创建数组后我不需要更改它)但后者让我崩溃。
...
[self performSelectorInBackground:@selector(loadImageArrays) withObject:nil];
...
- (void)loadImageArrays {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
NSString *fileName;
imageArray = [[NSMutableArray alloc] init];
for(int i = 0; i <= x; i++) {
fileName = [NSString stringWithFormat:@"image_0000%d.png", i];
[imageArray addObject:[UIImage imageNamed:fileName]];
}
[pool drain];
}
对比
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
imageArray = [[NSArray alloc] initWithObjects:
[UIImage imageNamed:@"image_00000.png"],
[UIImage imageNamed:@"image_00001.png"],
[UIImage imageNamed:@"image_0000X.png"],
nil];
[pool drain];
NSZombieEnabled = YES 告诉我在使用后一个代码片段时 [UIImage retain] 被发送到解除分配的实例。 这两个数组在我的 h 文件中都有 (nonatomic, retain) 属性。为什么图像没有被 NSArray 保留?
最佳答案
UIImage
是 UIKit 的一部分,它不是线程安全的。例如,imageNamed:
方法可能会破坏 UIImage
类用于缓存的全局名称-图像字典。
如果你想在后台线程上加载图像,你必须使用 Core Graphics。
编辑以回答您的评论:
您可以加载 PNG 文件:
CGDataProviderRef source = CGDataProviderCreateWithURL((CFURLRef)url);
CGImageRef image = CGImageCreateWithPNGDataProvider(source, NULL, NO, kCGRenderingIntentDefault);
CFRelease(source);
CGImage
是核心基础对象,可以存储在 NSArray
中。然后您可以从中创建一个 UIImage
(当然是在主线程上):
[[UIImage alloc] initWithCGImage:image]
关于cocoa-touch - 使用 initWithObjects 将图像加载到 NSArray 会崩溃,但使用 NSMutableArray 不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140932/