Reputation: 359
I have the following piece of code:
NSString *tempString = [[NSString alloc] initWithFormat:@"%d/%d/%d",day, month, year];
dateString = tempString;
[tempString release];
NSLog(@"retain count for datstring and tempstring is %d and %d",[dateString retainCount],[tempString retainCount]);
NSLog(@"%@ and %@",dateString, tempString)
Now it prints the retain count of tempString as 1 (also dateString retain count = 1) even though I am releasing it in the line before. Also the NSlog statement printing the two strings doesn't display anything. Im assuming this is because, since by my code, dateString is pointing to the location of tempString and tempString has been released, NSlog will be unable to print the string. But then why is the retain count of tempString = 1?
If i replace the line
dateString = tempString;
with
dateString = [NSString stringWithString: tempString];
then the NSlog statement prints the values of both dateString and tempString and displays their retain counts as 1. How is the value of tempString getting printed when i am releasing it in the previous line?
Upvotes: 1
Views: 88
Reputation: 2165
Read the iphone documentation:
You should not use
retainCount
to debug memory management issues.
As jamapag states release
simply tells the runtime to run dealloc
meaning that the memory is marked as reusable not that it has been cleared. For objects with a retainCount
of 1, the runtime usually doesnt decrement the retainCount
value after the dealloc
.
Another thing to note is that you should not send messages to released objects as you are doing with retainCount
you are bound to get some unexpected behaviours
Upvotes: 2
Reputation: 9318
When you send release to tempString the objc runtime simply calls dealloc. Just because an object has been sent dealloc doesn't mean its data on the heap is immediately destroyed. It's just marked for destruction later.
Upvotes: 0