gpt4 book ai didi

iphone - Objective-C NSString malloc 错误

转载 作者:行者123 更新时间:2023-12-03 20:22:00 25 4
gpt4 key购买 nike

我有一个方法可以创建一个字符串,然后在其上附加其他字符串:

-(NSString*)returnDetails {
NSString *details = [[NSString alloc] init];

details = [details stringByAppendingString:url];
details = [details stringByAppendingString:@" : "];
details = [details stringByAppendingString:author];

return [details autorelease];
}

我收到此错误:

iphoneapp_1(66508,0xacd9e2c0) malloc: *** error for object 0x6b9eb80: pointer being freed was not allocated

如果我把它改成

NSString *details = [NSString string];

并删除自动释放调用,然后它就可以工作了。我只是想了解为什么这有效而我原来的方法无效?

最佳答案

NSString 的方法 stringByAppendingString: 返回一个已经自动释放的对象。因此,从您的方法返回 [details autorelease] 将使该对象将被释放一次。只需返回详细信息即可。

那里还存在内存泄漏,因为您从未释放在方法顶部分配的字符串。试试这个代码:

-(NSString*)returnDetails {
NSString *details = [NSString string];
details = [details stringByAppendingString:url];
details = [details stringByAppendingString:@" : "];
details = [details stringByAppendingString:author];

return details;

}

关于iphone - Objective-C NSString malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9974281/

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