简单 UIImageView 数组上的 EXC_BAD_ACCESS
这段代码有什么问题?
在界面中:
NSArray *myImages;
@property (nonatomic, retain) NSArray *myImages;
实现:
NSArray *array = [NSArray arrayWithObjects:
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]],
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image2.png"]],
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image3.png"]],
nil];
self.myImages = array;
[array release];
如果我在初始化后立即记录 myImages,它会正确记录 UIImageViews 数组。但是,稍后在应用程序中,当我尝试从不同的方法访问 self.myImages 时,我得到 EXC_BAD_ACCESS。它被保留在界面中。问题是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要释放
数组
。使用arrayWithObjects:
,它将返回一个自动释放的对象。从某种意义上说,你释放了它两次。另一种方法是:然后您可以释放
array
。请参阅 Apple 的内存管理文章:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html%23//apple_ref/doc/uid/20000043-BEHDEDDB
Do not release
array
. UsingarrayWithObjects:
, it will return an autoreleased object. In a sense, you are releasing it twice. An alternative is:Then you can release
array
.See Apple's memory management article:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html%23//apple_ref/doc/uid/20000043-BEHDEDDB
arrayWithObjects 是一个方便的方法,它返回一个自动释放的对象,因此
通过这样做可以消除内存泄漏:
因为这次 imageView 没有被释放。
arrayWithObjects is a convenience method and returns an autoreleased object, so remove the
Plus you leak memory by doing this :
Because this time the imageView isn't released.
arrayWithObjects 返回一个自动释放的对象,你已经过度释放它了。请参阅此处http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/Articles/mmRules.html%23//apple_ref/doc/uid/20000994-BAJHFBGH
arrayWithObjects returns an autoreleased object, you're over releasing it. See here http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/Articles/mmRules.html%23//apple_ref/doc/uid/20000994-BAJHFBGH