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 alloc
the first string, then make a new autoreleased string from substringFromIndex:
, 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:
NSMutableString *myString = [[NSMutableString alloc] initWithString:@"This is my String"];
NSString *tmpString = [myString substringFromIndex:5];
NSLog(@"tempStr = %@", tempString);
[myString setString:tempStr];
// later do [myString release]
or even simpler:
NSString *myString = @"This is my String";
myString = [myString substringFromIndex:5];
You create an NSMutableString specifically so you CAN modify it.
But no one knows any way to do this:
[myMutableString substringFromIndex:5];
And if you are going to do this instead:
myMutableString = [myMutableString substringFromIndex:5];
why even use a mutable in the first place.
MutableStrings are great for ADDING (appending) to them.
Not sure why we can't also shorten (substring) them. (Without making a new copy.)
[myString substringFromIndex:5]
returns a new NSString
that starts from the specified index. It does not modify myString
.
try this code instead:
NSLog(@"myString = %@", [myString substringFromIndex:5]);
精彩评论