2011-10-07 60 views
1

我收到了錯誤消息,但不知道如何擺脫它。xcode,分析alloc錯誤

-- Method returns an Objective-C object with a +1 retain count (owning reference) 

--Object allocated on line 46 is not referenced later in this execution path and has a retain count of +1 (object leaked) 

線路AAA和bbb

+ (CustConf*) initEmptyCustConf { 
    CustConf* theObject = [[CustConf alloc] init]; 
    theObject.ID = 0; 
    theObject.aAA= [[NSString alloc] initWithString:@""]; 
    theObject.Number_Ndx = 0; 
    theObject.bBB = [[NSString alloc] initWithString:@""]; 

    return [theObject autorelease]; 
} 

回答

1

[[NSString alloc] initWithString:@""];是不必要的。只需使用@""

更改initEmptyCustConf此:

+ (CustConf *) initEmptyCustConf { 
    CustConf *theObject = [[CustConf alloc] init]; 
    theObject.ID = 0; 
    theObject.aAA = @""; 
    theObject.Number_Ndx = 0; 
    theObject.bBB = @""; 
    return [theObject autorelease]; 
} 
+0

ok,但爲什麼?(對不起,如果這是基本的) 來自[CustConf alloc] init的對象是否自動擁有一個retaincount爲1? – Franck

+0

我不確定,你能否顯示CustConf.m文件的代碼?然後我可以看到,但只是分配應該給你一個保留計數,然後autoreleasing(這是正確的事情)將在未來某個時候。所以這都是正確的。它必須是'CustConf'類的'alloc'或'init'方法中的東西。 – chown

+0

更多關於theObject.aAA = @「」與theObject.aAA = [[NSString alloc] initWithString:@「」] 即使我需要設置一個值,不需要分配它嗎? [[NSString alloc] initWithString:@「My int value」]; – Franck

1

我假設你已經定義了CustConf類保留的屬性。由於theObject會自動保留字符串aAA和bBB,並且在方法結束之前還沒有在代碼中釋放它們,所以最終會泄漏內存。

+ (CustConf*) initEmptyCustConf { 
    CustConf* theObject = [[CustConf alloc] init]; 
    theObject.ID = 0; 
    theObject.aAA= [[NSString alloc] initWithString:@""]; //potential leak 
    theObject.Number_Ndx = 0; 
    theObject.bBB = [[NSString alloc] initWithString:@""]; //potential leak 

    return [theObject autorelease]; 
} 

要解決這個問題,你需要明確釋放通過釋放/自動釋放分配給theObject.aAA和theObject.bBB琴絃,或只是使用字符串常量。

+ (CustConf*) initEmptyCustConf { 

    CustConf* theObject = [[CustConf alloc] init]; 
    theObject.ID = 0; 
    theObject.aAA= @""; 
    theObject.Number_Ndx = 0; 
    theObject.bBB = @""; 

    return [theObject autorelease]; 
} 

另外,如果你的方法與「初始化」開始,這是自返回一個保留的對象,所以無論是在年底卸下自動釋放,或更改方法的名稱,以反映你的方法的性質。

+0

'init'不會返回保留對象,'alloc','copy'和'new'。 – hypercrypt

+0

實際上,分析儀應該抱怨這一點。試試看。 – futureelite7

+0

回來乾淨。我同意方法名稱不好,不應該使用,但init不會返回保留的對象,它會返回self,替代self或nil。如果'init'返回一個保留對象'[[NSObject alloc] init]'+2 – hypercrypt