2011-09-27 60 views
0

仍在學習iOS開發具有的ObjectiveC和iOS,並試圖瞭解真的內存管理!欣賞下面的代碼片段任何意見,如: 1)分析說,有潛在的內存泄漏,但解決不了呢? 2)我應該保持alloc和初始化NSString在for循環中,並且當附加到?iOS的內存管理和NSString的初始化

感謝

- (NSString *) lookUpCharNameForID: (NSString *) inCharID 
{ 
    debugPrint ("TRACE", [[@"Lookup Char Name for = " stringByAppendingString: inCharID] UTF8String]); 


    NSString *tempName = [[NSString alloc] initWithFormat: @""]; 
    if (![inCharID isEqualToString: @""]) 
    { 
     // Potentially lookup multiple values 
     // 
     NSString *newName = [[NSString alloc] initWithFormat: @""]; 
     NSArray *idList  = [inCharID componentsSeparatedByString: @","]; 
     for (NSString *nextID in idList) 
     { 
      NSLog(@"Lookup %i : %@", [idList count], nextID); 
      newName = [[NSString alloc] initWithFormat: @"C%@", nextID]; 

      // Append strings 
      if ([tempName isEqualToString: @""]) 
       tempName = [[NSString alloc] initWithFormat: @"%@", newName]; 
      else 
       tempName = [[NSString alloc] initWithFormat: @"%@+%@", tempName, newName]; 
     } 
     [newName release]; 
    } 

    return [tempName autorelease]; 
} 

回答

3

您不需要撥打allocreleaseautorelease的任何呼叫。而是使用[NSString stringWithFormat:]來創建您不擁有的NSString實例,因此無需進行管理。此外,考慮使用NSMutableString簡化代碼有點,例如沿着以下(未經測試)版的臺詞:

- (NSString *) lookUpCharNameForID: (NSString *) inCharID 
{ 
    NSMutableString *tempName = nil; 

    if (![inCharID isEqualToString: @""]) 
    { 
     NSArray *idList = [inCharID componentsSeparatedByString: @","]; 

     for (NSString *nextID in idList) 
     { 
      [tempName appendString:@"+"]; // Does nothing if tempName is nil. 

      if (tempName == nil) 
       tempName = [NSMutableString string]; 

      [tempName appendFormat:@"C%@", nextID]; 
     } 
    } 

    return tempName; 
} 
+0

感謝那很多很多整潔;我沒想到,雖然你應該initwithformat使用,但沒有真正理解爲什麼 – DSDev

+0

到'alloc'應始終以一個'初始化...'方法的調用成對的呼叫。當你調用'alloc'時,你將獲得它返回的對象的所有權,並且必須通過向對象發送'release'或'autorelease'消息來放棄所有權。這是真正有用的閱讀,或者至少脫脂,蘋果的內存管理指南,以獲得更完整的畫面:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html – jlehr

0

你有2 tempName ALLOC initWithFormat。一個在循環之前,一個在循環之內。

0

使用ARC(自動引用計數)爲新項目。對於較舊的項目,可能很容易將其轉換,如果不是,可以根據需要逐個文件地禁用ARC。

使用可變的字符串,自動釋放便於學習方法和一點點rerfactoring:

- (NSString *) lookUpCharNameForID: (NSString *) inCharID 
{ 
    NSMutableString *tempName = [NSMutableArray array]; 

    if (inCharID.length) 
    { 
     NSArray *idList = [inCharID componentsSeparatedByString: @","]; 
     for (NSString *nextID in idList) 
     { 
      if (tempName.length == 0) 
       [tempName appendFormat: @"%@C", nextID]; 
      else 
       [tempName appendFormat: @"+%@C", nextID]; 
     } 
    } 

    return tempName; 
} 
+0

謝謝你也會試試這個 – DSDev