0
votes

This is my string:

2011-10-07T08:55:16-05:00

I am trying to remove the colon with this code:

NSRange range = NSMakeRange(dateString.length-3, 1);
NSString *temp = [dateString substringWithRange:range];
if ([temp isEqualToString:@":"])
    [dateString replaceCharactersInRange:range withString:@""];

My code enters the if statement, so I know that it found the colon. But it crashes with no errors on the last line. What am I doing wrong?

1
I suspect that dateString is not retained, and when you create temp it stomps on dateString. (You should show the logic that creates dateString.)Hot Licks
substringWithRange: won't alter the source (dataString) object, so it won't "stomp". My guess is dataString is not actually mutable (NSMutableString).gschandler
@HotLicks if dateString was not retained (-> released) the code would crash on dateString.length in line 1. I suspect you referred to an autoreleased dateString, but an autoreleased object would most certainly not "get stomped" by any other object. Autoreleased objects are released at the end of the runloop, which means "when your code exit and the app idles" almost all the time.Ahti
@Ahti -- Nope, the code wouldn't crash until another object is allocated over the top of dateString. But that other object is being allocated when temp is created. Have seen this sort of thing on several occasions.Hot Licks
@gschandler -- If dateString has been released but not yet overwritten then, indeed, substringWithRange (or any other operation that creates an object of the right size) can stomp on it.Hot Licks

1 Answers

0
votes

try this :

NSMutableString *dateString = [NSMutableString stringWithString:@"2011-10-07T08:55:16-05:00"];

NSRange range = NSMakeRange(dateString.length-3, 1);
NSString *temp = [dateString substringWithRange:range];
if ([temp isEqualToString:@":"])
    [dateString replaceCharactersInRange:range withString:@""];