2011-04-08 70 views
0

爲什麼當我嘗試釋放用+ imageNamed創建的圖像時,應用程序崩潰:dealloc內部。我的代碼如下:當使用+ imageNamed創建的uiimage在dealloc中釋放時,應用程序崩潰

MyClass.h:

#import <UIKit/UIKit.h> 
@interface MyClass{ 
    UIImage *_thumbImage; 
} 
@property (nonatomic,retain) UIImage *thumbImage; 
@end 

MyClass.m:

#import "MyClass.h" 
@implementation MyClass 
@synthesize thumbImage = _thumbImage; 
-(void)viewDidLoad{ 
    [super viewDidLoad]; 
    self.thumbImage = [UIImage imagedNamed:@"myImage.png""]; 
} 
-(void)viewDidUnload{ 
    self.thumbImage = nil; 
} 
-(void)dealloc{ 
    [super dealloc]; 
    [_thumbImage release]; //if i leave this here, the app crashes. should i release my property? 
} 


@end 

回答

3

在你的dealloc方法中,你需要將[super dealloc]移動到底部。你正在試圖在你的對象的實例變量被處理後訪問它。

+1

thx它的工作。所以應該在dealloc方法的結尾總是調用[super dealloc]?我認爲超級dealloc只是刪除父類中的實例變量,爲什麼它會影響我的子類中的Ivars的保留數? – prostock 2011-04-08 17:25:20

+1

[super dealloc]不會更改實例變量的保留計數。它告訴操作系統你的對象的內存可以被釋放。所以,當你嘗試訪問實例變量後,你引用了你不再擁有的內存。 – cduhn 2011-04-08 17:36:19

+0

...所以是的。總是最後調用[super dealloc]。 – cduhn 2011-04-08 17:37:03

0

[UIImage的imagedNamed:@ 「myImage.png」「];

是自動發佈的,它也是爲你管理的內存,如果你需要立即釋放它,那麼alloc/init一個UIImage或創建UIIm ageView。

#import <UIKit/UIKit.h> 
@interface MyClass{ 
} 
@end 


#import "MyClass.h" 
@implementation MyClass 
-(void)viewDidLoad{ 
    [super viewDidLoad]; 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRect(0,0,100,200)]; 
    imageView.image = [UIImage imagedNamed:@"myImage.png""]; 
    [self.view addSubView:imageView]; 
    [imageView release]; 
} 
-(void)viewDidUnload{ 
} 
-(void)dealloc{ 
    [super dealloc]; 
} 
+0

二傳手會自動保留它。 – JustSid 2011-04-08 17:19:03

+0

@cduhn答案解決了這個問題,但如果你不需要保留圖像,那麼我會按照自己的方式去做。 – Jordan 2011-04-08 17:29:47

+0

刪除David的thumbImage屬性不是必需的。你假設他想把它分配給UIImageView並顯示它。他可能想爲其他原因保存對它的引用。 – cduhn 2011-04-08 17:31:28

-1

您可能想要查看蘋果的內存管理指南這裏:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

特別是部分指出:

,如果你使用的方法創建你需要一個對象的所有權其名稱以「alloc」,「new」,「copy」或「mutableCopy」(例如alloc,newObject或mutableCopy)開頭,或者如果您向其發送保留消息。

由於您沒有使用這些功能之一,因此您沒有該對象的所有權,因此無法釋放它。

+0

這是正確的,但他將圖像分配給一個保留屬性=>它應該被釋放。 – SVD 2011-04-08 17:13:07

0

你需要首先發布你的東西,然後致電[super dealloc][super dealloc]將釋放類的內存並在之後訪問ivar會導致段錯誤。

相關問題