gpt4 book ai didi

objective-c - Objective-C-NSMutableAttributedString 泄漏

转载 作者:行者123 更新时间:2023-12-03 17:36:03 26 4
gpt4 key购买 nike

我是 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];
}

谁能解释一下为什么吗?

最佳答案

第一个示例的问题是额外的保留。您需要删除它,因为当您使用 [[NSMutableAttributedString alloc] initWithString:@"Hello "]; 创建 textViewAttrStr 时它已被保留;

//Remove this line in the first example
[textViewAttrStr retain];

关于objective-c - Objective-C-NSMutableAttributedString 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7027550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com