我每天都在尝试使用牙线,锻炼身体,并确保在保留和释放之间保持平衡。
这让我感到困惑。我有一个伊瓦尔:
NSMutabledata *_alignmentData
以及与之相关的综合属性:
// .h file
@property (nonatomic, retain) NSMutableData *alignmentData;
// .m file
@synthesize alignmentData=_alignmentData;
我开始从服务器异步拉取数据:
self.connection =
[[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];
并在分配数据缓冲区后立即在异步回调中使用:
// 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]);
为了使在上述 self.alignmentData 分配后触发的第一个异步回调中的问题复杂化,我再次检查保留计数:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// This prints 1.
NSLog(@"[_alignmentData retainCount] = %d", [_alignmentData retainCount]);
[self.alignmentData setLength:0];
}
因此,保留计数似乎从 0 上升到 2,然后下降到 1。有人可以向我解释这是怎么可能的吗?
注意:我被告知不要使用保留计数作为调试辅助,但这在非垃圾收集语言(如 Objective-C)中根本不实用。