Question

I created a custom NSString Category which lets me find all strings between two other strings. I'm now running into the problem of finding that there are a lot of kBs leaking from my script. Please see code below:

    #import "MyStringBetween.h"

@implementation NSString (MyStringBetween)

-(NSArray *)mystringBetween:(NSString *)aString and:(NSString *)bString;
{
    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];

    NSArray *firstlist = [self componentsSeparatedByString:bString];
    NSMutableArray *finalArray = [[NSMutableArray alloc] init];


    for (int y = 0; y < firstlist.count - 1 ; y++) {
        NSString *firstObject = [firstlist objectAtIndex:y];
        NSMutableArray *secondlist = [firstObject componentsSeparatedByString:aString];
        if(secondlist.count > 1){

            [finalArray addObject:[secondlist objectAtIndex:secondlist.count - 1]];
        }
    }

    [autoreleasepool release];

    return finalArray;
}
@end

I admit that I'm not super good at releasing objects, but I had believed that the NSAutoreleasePool handled things for me.

The line that is leaking:

NSMutableArray *secondlist = [firstObject componentsSeparatedByString:aString];

Manually releasing secondlist raises an exception.

Thanks in advance!

Was it helpful?

Solution

No, this is the line that is leaking:

NSMutableArray *secondlist = [[NSMutableArray alloc] init];

And it isn't that big of a leak (just an empty mutable array). Still, don't do that.

In particular, the line:

    secondlist = [[firstlist objectAtIndex:y] componentsSeparatedByString:aString];

Is assigning over the reference to the empty mutable array.

Also FinalArray should be named finalArray.

OTHER TIPS

finalArray is leaking. You should autorelease it before returning it but make sure you do it either before allocating the autorelease pool or after releasing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top