Objective c 返回UIImage时EXC\u访问错误

Objective c 返回UIImage时EXC\u访问错误,objective-c,ios4,uiimage,exc-bad-access,Objective C,Ios4,Uiimage,Exc Bad Access,我有一个方法,它应该返回从contentsOfFile创建的UIImage(以避免缓存),但当它返回时,我收到EXC_BAD_访问。在仪器中运行不会显示任何结果,因为它只是运行,不会在僵尸身上停止 映像已在捆绑资源阶段正确复制 - (UIImage *)imageForName:(NSString *)name { NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"]; return

我有一个方法,它应该返回从contentsOfFile创建的UIImage(以避免缓存),但当它返回时,我收到EXC_BAD_访问。在仪器中运行不会显示任何结果,因为它只是运行,不会在僵尸身上停止

映像已在捆绑资源阶段正确复制

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

该方法改编自PhotoScroller样本,该样本工作正常

谢谢

编辑:

这是使用imageForName的代码,您可以看到,根据Luke/T的建议,我添加了retain,但是EXC_BAD_访问在返回中,而不是我的addObject:call:

NSMutableArray *images;

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

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

编辑:

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

e、 g


将对象添加到
NSMutableArray
将隐式地向其发送
retain
,因此代码中不需要这样做

您是否可以确认(使用
NSLog()
或断点)

[UIImage imageWithContentsOfFile:path]


返回
imageForName:
方法中的对象?

最后,此代码应为:

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];

我们需要查看使用imageForName的代码,请参阅Luke的回答。不过,不要将其保留在
imageForName:
本身中。我更改了上面的代码,以显示我执行此操作时发生的情况。这就像是找不到图像一样,但我不会得到零。
NSMutableArray *images = [[NSMutableArray alloc] init];//release later
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];