2011-02-02 16 views
1

這段代碼有什麼問題?簡單的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。它被保留在界面中。問題是什麼?

回答

5

不要釋放array。使用arrayWithObjects:,它將返回一個自動釋放對象。從某種意義上說,你是釋放它兩次。替代方案是:

[[NSArray alloc]initWithObjects:...] 

然後您可以發佈array

看到蘋果的內存管理文章:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html%23//apple_ref/doc/uid/20000043-BEHDEDDB

+0

啊,當然。那是愚蠢的。 – sol 2011-02-02 22:34:38

2

arrayWithObjects是一個方便的方法,並返回一個自動釋放的對象,所以刪除

[array release]; 

另外,你做這個內存泄漏:

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

貝卡使用這個時候imageView不會被釋放。

+0

感謝您對UIImageView的注意事項 – sol 2011-02-02 22:35:09