gpt4 book ai didi

iphone - 重新分配变量时是否存在内存泄漏?

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

假设我有一个已经通过 alloc/init 组合初始化为字符串的变量。如果我通过处理重新分配它,会出现内存泄漏吗?

NSString *s = [[NSString alloc] initWithString:someOtherStringVariable];
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

这里有内存泄漏吗?如果是这样,我是否需要创建另一个变量(例如 s2),进行此赋值,然后释放原始变量?

NSString *s = [[NSString alloc] initWithString:someOtherStringVariable];
NSString *s2 = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[s release];

现在,如果其他字符串是常量,例如@“其他字符串”怎么办?我需要担心泄漏吗?即。

NSString *s = [[NSString alloc] initWithString:@"Some other string"];
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

谢谢

最佳答案

这绝对是一个泄漏。处理此类问题的最简单方法是尽早自动释放:

NSString *s = [[[NSString alloc] initWithString:@"Some other string"] autorelease];
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

您也可以使用 NSMutableString 就地执行此操作(如果这不是一个概念示例)。

关于iphone - 重新分配变量时是否存在内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1256031/

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