I'm inferring from the presence of retain
, that you're employing MRR (manual retain and release). In MRR, this code results in:
@implementation ABC
-(void) fun1
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = obj1; // unchanged
// you have one instance of `ObjectA` with a retain count of +1
// both `obj1` and `obj2` point to the same single instance
}
-(void) fun2
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = [obj1 retain]; // retainCount = +2
// you have one instance of `ObjectA` with a retain count of +2
// both `obj1` and `obj2` point to the same single instance
}
-(void) fun3
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 copy]; // retainCount of `obj2` object = +1
// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance and `obj2` point to the other
}
-(void) fun4
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 mutableCopy]; // retainCount of `obj2` object = +1
// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance
// `obj2` points to another instance, which is mutable copy of the `obj1` instance
}
@end
Clearly, in all of these cases, in MRR, if you don't do something with the ObjectA
instances by the end of the method, you'll be leaking (because you're abandoning the last known reference to these objects). If using ARC, the necessary clean up is performed.
By the way, in the future, you should examine the results yourself. For example, if you added these diagnostic statements to the end of each method, you'd clearly see what's going on:
NSLog(@"%s: [obj1 (%p) retainCount] = %d", __FUNCTION__, obj1, [obj1 retainCount]);
NSLog(@"%s: [obj2 (%p) retainCount] = %d", __FUNCTION__, obj2, [obj2 retainCount]);
That displays the address of the object to which the variable points, as well as the object's current retainCount
. Needless to say, you shouldn't be using retainCount
in production code, but it's useful solely for diagnostic purposes.
By way, while it's good that you're trying to understand the memory management, I would suggest that you seriously consider using automatic reference counting (ARC). It makes memory management much easier (no retain
, release
or retainCount
). And if you're determined to stick with manual retain and release (MRR), then make sure you run your code through the static analyzer ("Analyze" on Xcode's "Product" menu), as it's pretty decent in identifying the sort of problems that plague MRR code.