Csabi
Csabi

Reputation: 3043

why is code falling on substringwithrange

hi here is my function, but everytime when i try to init and alloc foo it falls, can you tell me why?

   -(NSString*)modifyTheCode:(NSString*) theCode{
        if ([[theCode substringToIndex:1]isEqualToString:@"0"]) {
            if ([theCode length] == 1 ) {
            return @"0000000000";
        } 
            NSString* foo = [[NSString alloc]initWithString:[theCode substringWithRange:NSMakeRange(2, [theCode length]-1)]];

            return [self modifyTheCode:foo];

        } else {

            return theCode;

        }


}

the error message:

warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).

Upvotes: 1

Views: 1769

Answers (3)

JeremyP
JeremyP

Reputation: 86691

Because the range is invalid. NSRange has two members, location and length. The range you give starts at the third character of the string and has the length of the string minus one. So your length is one character longer than the amount of characters left in the string.

Suppose theCode is @"0123". The range you create is { .location = 2, .length = 3 } This represents:

0123
  ^ start of range is here
     ^ start of range + 3 off the end of the string.

By the way, you'll be pleased to know that there are convenience methods so you don't have to mess with ranges. You could do:

if ([theCode hasPrefix: @"0"])
{

    NSString* foo = [theCode substringFromIndex: 1]; // assumes you just want to strip off the leading @"0"

    return [self modifyTheCode:foo];

} else {

    return theCode;

}

By the way, your original code leaked foo because you never released it.

Upvotes: 1

Krishnabhadra
Krishnabhadra

Reputation: 34296

replace this line

NSString* foo = [[NSString alloc]initWithString:[theCode substringWithRange:NSMakeRange(2, [theCode length]-1)]];

with this line

NSString* foo = [[NSString alloc]initWithString:[theCode substringWithRange:NSMakeRange(1, [theCode length]-1)]];

and try..

Upvotes: 1

TalkingCode
TalkingCode

Reputation: 13567

What is the error message? If you are working with NSRange maybe you should check the length of theCode first.

Upvotes: 1

Related Questions