views:

48

answers:

1

I'm using this function to extract a substring, it works but there are two leaks:

-(NSString*)EstraiP:(NSString*)str ini:(NSString*)ini fin:(NSString*)fin occ:(int)occ{

     NSRange rstr1;
     for(int i=0; i < occ; i++){
          rstr1=[str rangeOfString:fin];
          str=[str substringFromIndex:rstr1.location+rstr1.length];
     }

     NSString* FinalStr;
     rstr1=[str rangeOfString:ini];

     if(occ==0){
          if(rstr1.length==0)
               return @"Non Trovato inizio";
          FinalStr=[str substringFromIndex:(rstr1.location +  rstr1.length)] ;
     }else{
          if(rstr1.length==0)
               return @"Non Trovato inizio";
          FinalStr=[str substringFromIndex:rstr1.location+rstr1.length] ;
     }

     NSRange rstr2=[FinalStr rangeOfString:fin];
     if(rstr2.length==0)
          return @"Non Trovata fine";
     FinalStr=[FinalStr substringToIndex:rstr2.location];

     return FinalStr;
}

This to lines leak some memory:

str=[str substringFromIndex:rstr1.location+rstr1.length];

FinalStr=[FinalStr substringToIndex:rstr2.location];

i looked around but did find nothing.... There is no alloc or retain so i shouldn' be releasing them...what can be the problem? i hope i explained myself

Thanks!

A: 

Your initial for loop is likely to throw an exception. -[NSString rangeOfString:] returns an NSRange object with the location field set to NSNotFound if no match was found. In this case, you'll end up trigger an exception when you plug that value into -substringFromIndex:.

You should not be naming variables with an uppercase first letter. Such naming is generally reserved for class names and makes your code very confusing to read.

Instead of using aRange.location + aRange.length you may want to use NSMaxRange(aRange). It compiles to the exact same thing, but it's a bit more readable.

And finally, you have no memory leaks. Why do you think there is one?

Kevin Ballard