I am trying to floss daily, get my exercise, and make sure I maintain a balance between my retains and releases.
Here is what has me puzzled. I have a ivar:
NSMutabledata *_alignmentData
and a synthesized property associated with it:
// .h file
@property (nonatomic, retain) NSMutableData *alignmentData;
// .m file
@synthesize alignmentData=_alignmentData;
I start to pull data from a server asynchronously:
self.connection =
[[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];
And immediately after allocate a data buffer to be used subsequently in the asynchronous callbacks:
// This prints 0. Cool.
NSLog(@"BEFORE [_alignmentData retainCount] = %d", [_alignmentData retainCount]);
// Create a place to receive the data that will arrive asynchronously:
self.alignmentData = [NSMutableData data];
// This prints 2. Shouldn't this be 1 ?!?
NSLog(@" AFTER [_alignmentData retainCount] = %d", [_alignmentData retainCount]);
To complicate matters in the first asynchronous callback that fires after the above allocation of self.alignmentData, I inspect the retain count again:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// This prints 1.
NSLog(@"[_alignmentData retainCount] = %d", [_alignmentData retainCount]);
[self.alignmentData setLength:0];
}
So, it appears that the retain count rises to 2 from 0 then drops to 1. Can someone explain to me how this is possible?
Note: I've been told not to use retain counts as a debugging aid but that is simply not practical in a non-garbage collected language such as Objective-C.