My question is that why does my retain count drop back to 1 if I call
myString = [[NSMutableString alloc] init]; again?
Because you are failing to understand a very basic concept of Objective-C; myString is not an instance of an NSMutableString, but a reference to an instance. If you were to:
myString = [[NSMutableString alloc] init];
myString = [[NSMutableString alloc] init];
You now have two instances of NSMutableString, one leaked.
If you:
myString = [[NSMutableString alloc] init];
otherString = myString;
You now have a single instance of NSMutableString with two references.
In all three allocations, the NSMutableString instance will have a +1 retain count and, thus, you must balance each with a single release or you'll leak.
Treating retain counts as an absolute count is a path to madness. Or, at best, the scope of usefulness of the absolute retain count is so limited that learning about it is not applicable to real world iOS programming.
This bears repeating:
The retainCount of an object is tricky business.
If you were to continue down this path, you should be aware of the following details:
retainCount can never return 0
- messaging a dangling pointer is not guaranteed to crash
- retain count cannot be known once you have passed an object through any system API due to implementation details
- any subclass of any system class may have an unknown retain count due to implementation details
- retain count never reflects whether or not an object is autoreleased
- autoreleases is effectively thread specific while the retain count is thread global
- some classes are implemented with singletons some of the time (NSString, certain values of NSNumber)
- the implementation details change from platform to platform and release to release
- attempting to swizzle
retain/release/autorelease won't work as some classes don't actually use those methods to maintain the retain count (implementation detail, changes per platform/release, etc..)
If you are going to teach retain/release, you should be treating the retain count as a delta and focus entirely on "If you increase the RC, you must decrease it".
-retainCountnear bbum is like waving a red flag in front of a bull. - Brad LarsonretainCountuntil the last paragraph of the new part. As for the comment, well, it was a comment... not an answer. - bbumretainCountfully and why it is misleading, using it to teach your students will teach them thatretainCountis useful for learning and/or debugging. Better to remove theretainCountdisplay in the app and use Instruments to view an object's history live as you hit the buttons: then you teach them a useful debugging technique and don't implicitly teach them to useretainCount. - Peter Hosey