开发者

Problem with leaking NSStrings

开发者 https://www.devze.com 2023-01-18 17:18 出处:网络
My code leaks but I do not know exactly what am I doing wrong. Simply I have a function that takes array with NSStrings and outputs NSString formatted as CSV.

My code leaks but I do not know exactly what am I doing wrong. Simply I have a function that takes array with NSStrings and outputs NSString formatted as CSV.

Here is my code:

-(NSString*)generateCSVfromArray: (NSMutableArray*) reportEntries {

    NSString* accumulator = [NSString stringWithString:@""];

    for (NSString* string in reportEntries) {

        NSString* temp = [accumulator stringByAppendingString:string];
        accumulator = temp;

        if (![string isEqualToString:@"\n"]) {

            NSString* temp = [accumulator stringByAppendingString:@";"];
            accumulator = temp;
        }
    }
    return accumulator;
}

When I check leaks in Instruments it turns out that many string objects开发者_JS百科 leaked. I managed to isolate the problem to the method above. Can you please help me and point what am I doing wrong?


I don't believe you're leaking any strings in this method. Why do you think this is the method to blame? Remember that Instruments will tell you where the object was created, but this has little to do with where it is leaked. Run the Static Analyzer for more help with that (Cmd-Shift-A).

This method is wildly inefficient, though. You're creating a ton of temporary strings. You could write this much more efficiently like this:

-(NSString*)generateCSVfromArray:(NSArray*)reportEntries {

    NSMutableString* accumulator = [NSMutableString string];

    for (NSString* string in reportEntries) {

        [accumulator appendString:string];

        if (![string isEqualToString:@"\n"]) {
            [accumulator appendString:@";"];
        }
    }
    return accumulator;
}

There are of course very good CSV writers already available. Search for "Cocoa CSV." But I assume you want this specialized algorithm.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号