我是 Obj-C 的新手,并且正在尝试一些东西。我偶然发现了一个泄漏问题,并想知道其背后的逻辑原因。
以下代码泄漏:
(textViewAttrStr is an instance variable of type NSMutableAttributedString)
-(void) init:(NSString*)str
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
textViewAttrStr = [[NSMutableAttributedString alloc] initWithString:@"Hello "];
NSMutableAttributedString *part1String = [[NSMutableAttributedString alloc] initWithString:str];
[textViewAttrStr appendAttributedString:part1String];
NSMutableAttributedString *part2String = [[NSMutableAttributedString alloc] initWithString:@"!!!"];
[textViewAttrStr appendAttributedString:part2String];
[textViewAttrStr retain];
[part1String release];
[part2String release];
[pool drain];
}
-(void) dealloc
{
if(textViewAttrStr != nil)
{
[textViewAttrStr release];
}
[super dealloc];
}
而以下代码不会泄漏:
-(void) init:(NSString*)str
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableAttributedString* tvas = [[NSMutableAttributedString alloc] initWithString:@"Hello "];
NSMutableAttributedString *part1String = [[NSMutableAttributedString alloc] initWithString:str];
[tvas appendAttributedString:part1String];
NSMutableAttributedString *part2String = [[NSMutableAttributedString alloc] initWithString:@"!!!"];
[tvas appendAttributedString:part2String];
textViewAttrStr = tvas;
[textViewAttrStr retain];
[part1String release];
[part2String release];
[tvas release];
[pool drain];
}
-(void) dealloc
{
if(textViewAttrStr != nil)
{
[textViewAttrStr release];
}
[super dealloc];
}
有人可以解释为什么吗?