2012-03-05 54 views
11

我得到這個警告後放行自動引用計數問題:將保留對象分配給unsafe_unretained變量;對象將分配

「自動引用計數的問題:分配保留對象unsafe_unretained變量;對象將分配後發佈」

下面是代碼

.H

@interface myObject : NSObject 
{ 
} 

@property (assign) id progressEnergy; 

@end 

.M

@implementation myObject 

@synthesize progressEnergy; 

-(id)init 
{ 
    if ((self = [super init])) 
    { 
     progressEnergy = [[progress alloc] init]; //warning appear on this line 
    } 

    return self; 
} 

@end 

我已經嘗試

@property (assign) progress* progressEnergy; 

,但沒有運氣

能否請你幫我弄清楚什麼是錯的?

回答

27

變化

@property (assign) progress* progressEnergy; 

@property (strong) progress* progressEnergy; 

讓你myObject保留progress對象。

+0

謝謝。這是問題:) – zeroonnet 2012-03-06 20:32:25

9

這是警告你,你正在分配一個即將在封閉範圍的末尾釋放的值,這恰好是下一行。因此,這是你的init的樣子ARC在它的神奇之後補充說:

-(id)init 
{ 
    if ((self = [super init])) 
    { 
     progressEnergy = [[progress alloc] init]; 
     [progressEnergy release]; ///< Release progressEnergy since we've hit the end of the scope we created it in 
    } 

    return self; 
} 

所以你progressEnergy現在是極有可能(雖然不一定)是一個懸擺指針。

變化從assign屬性的定義strong

@property (strong) progress* progressEnergy; 

在這種情況下,你的init方法是這樣的:

-(id)init 
{ 
    if ((self = [super init])) 
    { 
     progressEnergy = [[progress alloc] init]; 
     [progressEnergy retain]; ///< Since it's a strong property 
     [progressEnergy release]; ///< Release progressEnergy since we've hit the end of the scope we created it in 
    } 

    return self; 
} 

其實不然,它會調用objc_storeStrong而不是調用的retain就像我已經展示的那樣,但本質上它歸結爲retain在這種情況下。

+0

謝謝。這是問題:) – zeroonnet 2012-03-06 20:32:38

相關問題