【问题标题】:EXC_BAD_ACCESS when returning UIImage返回 UIImage 时的 EXC_BAD_ACCESS
【发布时间】:2010-11-17 10:55:46
【问题描述】:

我有一个方法应该返回从 contentsOfFile 创建的 UIImage(以避免缓存),但是当它返回时,我收到 EXC_BAD_ACCESS。通过 Instruments 运行不会显示任何结果,因为它只是运行,不会在僵尸上停下来。

图片在Bundle Resources阶段正确复制...

- (UIImage *)imageForName:(NSString *)name {
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
    return [UIImage imageWithContentsOfFile:path];

}

此方法改编自 PhotoScroller 示例,可以正常工作。

谢谢

编辑:

这是使用 imageForName 的代码,您可以看到我根据 Luke/T 的建议添加了保留,但返回的是 EXC_BAD_ACCESS,而不是我的 addObject: 调用:

NSMutableArray *images;

for (NSDictionary *dict in imageListForPage){
    [images addObject:[[self imageForName:[dict valueForKey:@"name"]]retain]];
}

【问题讨论】:

  • 我们需要看一下使用imageForName的代码,看Luke的回答

标签: objective-c ios4 uiimage exc-bad-access


【解决方案1】:

ImageWithContentsOfFile 将返回一个自动释放的对象。如果您不保留它(返回时[编辑]),那么您将获得错误的访问权限。

编辑:

检查 NSarray 的指针。您需要像平常一样初始化数组 alloc 或使用 arraywith

例如

NSMutableArray *images = [NSMutableArray arrayWithCapacity:ARRAY_CAPACITY];//autoreleased

NSMutableArray *images = [[NSMutableArray alloc] init];//release later

【讨论】:

  • 不过,不要将其保留在 imageForName: 本身中。
  • 我更改了上面的代码,以显示我这样做时会发生什么。好像找不到图像,但我没有得到零。
【解决方案2】:

将对象添加到NSMutableArray 将隐式发送retain,因此在您的代码中没有必要这样做。

您能否确认(使用NSLog() 或断点)

[UIImage imageWithContentsOfFile:path]

在您的 imageForName: 方法中返回一个对象?

【讨论】:

    【解决方案3】:

    最后,这段代码应该是:

    NSMutableArray *images = [NSMutableArray new]; // new is same as [[alloc] init]
    
    for (NSDictionary *dict in imageListForPage) {
      [images addObject:[self imageForName:[dict valueForKey:@"name"]]];
    }
    // ... do something with images
    [images release];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 2023-03-09
      • 2012-03-17
      相关资源
      最近更新 更多