iOS内存管理& NSString初始化

时间:2011-09-27 18:26:09

标签: ios memory-leaks nsstring

仍在使用ObjectiveC和iOS学习iOS开发,并尝试真正了解内存管理!感谢以下片段的任何建议,例如: 1)分析仪表示存在潜在的内存泄漏,但无法解决? 2)我是否应该在for循环中保留alloc并初始化NSStrings并将其附加到?

由于

- (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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

你有2个为tempName分配initWithFormat。一个在循环之前,一个在循环之内。

答案 2 :(得分:0)

对新项目使用ARC(自动引用计数)。对于较旧的项目,转换它们可能很容易,如果不是,可以在必要时逐个文件地禁用ARC。

使用可变字符串,自动释放的方法和一点点重构:

- (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;
}