私は Obj-C の初心者で、いくつかのことを試しています。1 つのリークの問題に出くわしました。その背後にある論理的な理由を知りたいと思います。
次のコードがリークしています:
(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];
}
誰かが理由を説明できますか?