EXC_BAD_ACCESS on a simple array of UIImageViews
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"]开发者_如何学C],
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?
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
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.
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
精彩评论