2010-07-25 65 views
0

嘿,最近我一直在問iPhone的內存管理問題。幸運的是事情變得更加清晰。但是,當它變得更加複雜時,我仍然很掙扎:那麼就存儲器管理而言,這有什麼問題嗎?我的問題和建議在評論中...iPhone,客觀的c重新分配和返回方法的指針

//I get a text from a textfield 
NSString *text = [[NSString alloc]initWithString:txtField.text]; 
NSMutableString *newText = [self replaceDynamicRegex:text]; 
[text release]; 
... 

//The method replaces regex it finds in the text. The regex part is just pseudo code 
//and I just interested in memory management 
-(NSMutableString*)replaceDynamicRegex:(NSString*)txt{ 

NSString *currentTag = [NSString stringWithString:@"dynamiclyCreatedTag"]; 

//As long as we find a particuar regex (just pseuo code here) we replace it 
while (currentTag != NULL) { 

    if([html stringByMatching:openingTag] == NULL){ 
     break; 
    } 

    //regular expression 
    currentTag = [NSString stringWithString:[html stringByMatching:theRegex]]; 

    //Get rid of the useless part of the currentTag pseudo code 
    NSString *uselessTagPart = @"uselessRegex"; 
    //Reassignment of the pointer currentTag --> ok to do this? cause I did not alloc]init]? 
    //and instead used stringWithString wich then gets autoreleased 
    currentTag = [currentTag stringByReplacingOccurrencesOfRegex:uselessTagPart withString:@""]; 

    //Reassignment of the pointer html --> Ok to do this? cause it is just a pointer and the 
    //object is being released after the method call (further up) 
    html = (NSMutableString*)[html stringByReplacingOccurrencesOfRegex:currentTag withString:replacementTag]; 
    } 
    //Do I need to autorelease this? 
    return html; 
} 

回答

1

您的代碼看起來正確的內存管理方式。請記住,如果您沒有在方法名稱中調用方法alloc,new,retaincopy,則不必擔心釋放。

一個小問題 - 您的前三行代碼冗餘且效率低下。您通常不應該使用initWithString - copy通常是處理不可變對象時更好的選擇,因爲後面的方法可以用(較便宜的)retain方法代替。在你的情況下,你甚至不需要使用copy - [self replaceDynamicRegex: txtField.text]將會有相同的結果。同樣,您可以使用[html stringByMatching:theRegex](而不是[NSString stringWithString:[html stringByMatching:theRegex]])(因爲該方法返回一個新字符串)。

另一個說明 - html = (NSMutableString*)[html stringByReplacingOccurrencesOfRegex:currentTag withString:replacementTag]是不正確的。 stringByReplacingOccurrencesOfRegex:返回NSString,無法將其轉換爲NSMutableString(稍後在將更改方法發送到字符串時,可能會發生崩潰)。而是使用[[html stringByReplacingOccurrencesOfRegex:currentTag withString:replacementTag] mutableCopy]

+0

好的謝謝。但是,我將如何「釋放」mutableCopy呢?用autorelease:return [html autorelease]; ?!? – jagse 2010-07-25 19:42:01

+0

@jagse:是的,如果你複製它,你會想自動釋放它。 – shosti 2010-07-25 21:56:47

0

通常,當您看到名爲xWithY的方法時,可以假定該字符串將是autorelease -d。

因此,你可能做不是需要autorelease-stringByReplacingOccurrencesOfRegex:withString:返回的值。

其餘的代碼對我來說看起來沒問題。