[result release] alone doesn't crash the program


#1

Under the Autoreleasing Objects section…

Just by chance I didn’t code the [df release]; line and ran my code. It ran fine! When I added the [df release]; line, that’s when I saw the crash. Isn’t the “result” object an invalid pointer when I release it in the first example? How does NOT releasing the “df” object make a difference?

No crash:

- (NSString *)description { NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setTimeStyle:NSDateFormatterNoStyle]; [df setDateStyle:NSDateFormatterMediumStyle]; NSString *result; result = [[NSString alloc] initWithFormat:@"%@ = %d and %d", [df stringFromDate:entryDate], firstNumber, secondNumber]; [result release]; return result; }

Crash:

- (NSString *)description { NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setTimeStyle:NSDateFormatterNoStyle]; [df setDateStyle:NSDateFormatterMediumStyle]; NSString *result; result = [[NSString alloc] initWithFormat:@"%@ = %d and %d", [df stringFromDate:entryDate], firstNumber, secondNumber]; [result release]; [df release]; return result; }