views:

41

answers:

1

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 leaked. I managed to isolate the problem to the method above. Can you please help me and point what am I doing wrong?

+2  A: 

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.

Rob Napier
I was going to respond with the same code Rob posted. Good job Rob.
Jordan