【发布时间】:2011-10-25 01:08:33
【问题描述】:
我是 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];
}
谁能解释一下原因?
【问题讨论】:
-
感谢大家的快速回复。这使内存管理对我来说更容易一些。 :)
标签: objective-c cocoa memory-leaks nsmutablestring