2011-09-27 78 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