简单 UIImageView 数组上的 EXC_BAD_ACCESS

发布于 2024-10-15 06:33:12 字数 670 浏览 6 评论 0 原文

这段代码有什么问题?

在界面中:

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。它被保留在界面中。问题是什么?

What is wrong with this code?

in the interface:

NSArray *myImages;
@property (nonatomic, retain) NSArray *myImages;

implementation:

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

If I log myImages right after initializing it, it correctly logs the array of UIImageViews. However, later in the app, when I try to access self.myImages from a different method, I get EXC_BAD_ACCESS. It is getting retained in the interface. What is the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吝吻 2024-10-22 06:33:12

不要释放数组。使用arrayWithObjects:,它将返回一个自动释放的对象。从某种意义上说,你释放了它两次。另一种方法是:

[[NSArray alloc]initWithObjects:...]

然后您可以释放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. Using arrayWithObjects:, it will return an autoreleased object. In a sense, you are releasing it twice. An alternative is:

[[NSArray alloc]initWithObjects:...]

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

爱的故事 2024-10-22 06:33:12

arrayWithObjects 是一个方便的方法,它返回一个自动释放的对象,因此

[array release];

通过这样做可以消除内存泄漏:

[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]]

因为这次 imageView 没有被释放。

arrayWithObjects is a convenience method and returns an autoreleased object, so remove the

[array release];

Plus you leak memory by doing this :

[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]]

Because this time the imageView isn't released.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文