Why is substringFromIndex not working for my NSMutableString ?
Here code similar to what I have :
NSMutableString *myString = [[NSMutableString alloc] initWithString:@"This is my String"];
[myString substringFromIndex:5];
NSLog(@"myString = %@", myString); //will output This is my String
If I use substringFromIndex on NSString it will work, for example like so :
NSString *tempStr = [[NSString alloc] init];
tempStr = [myString substringFromIndex:5];
NSLog(@"tempStr = %@", tempStr); //will output is my String
Why does it not work in the first example, and I have one more question, if I do it using the second method, and then I set:
[myString setString:tempStr];
[tempStr release];
This will result in a crash, I thought, since I used setString on NSMutableString, that I do not need the NSString and I release it, but apparently that is not the case, however if I use autorelease it will be OK
That method never alters the string you call it on. It returns a new string in both cases. So assign it to a new string variable and your good.
It’s crashing because you over releasing one object and and leaking another. You
allocthe first string, then make a new autoreleased string fromsubstringFromIndex:, then release it. You dont need to try this hard.Simply assign the output of the substring method to a variable, and let it be autoreleased for you. No alloc, no release.
A full proper example might look like this:
or even simpler: