【问题标题】:Another iPhone Memory leak issue另一个 iPhone 内存泄漏问题
【发布时间】:2011-11-12 06:58:08
【问题描述】:

我在 jsonParser 上有内存泄漏。

这是我的代码

- (id) objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];

// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:nil]; }

这是我收到的错误消息,在第 192 行分配并存储到“jsonParser”中的对象可能泄漏

请帮忙。

【问题讨论】:

    标签: iphone objective-c memory-leaks sbjson


    【解决方案1】:

    +new 等效于 [[SBJsonParser alloc] init] 调用,因此您负责释放 jsonParser 对象。当您在 return 语句中使用它时,修复泄漏的最简单方法是在创建后立即自动释放它:

    SBJsonParser *jsonParser = [[SBJsonParser new] autorelease];
    

    【讨论】:

    • 此外,您应该考虑将allocinit 消息发送到类而不是new,虽然它们在功能上是等效的,但从技术上讲new 不是Objective-C 的一部分,而是不是社区广泛使用的东西。 Here are a few more reasons to use alloc and init instead of new.
    • @Thuggish:从技术上讲,allocinit 不是 Objective-C 的一部分。它们是 Foundation 框架的一部分。事实上new 早于它们并且实际上源自 Smalltalk。无论如何,你的观点是成立的。每个人都使用allocinitnew 在 Objective-C 的上下文中看起来有点奇怪。
    • 您可能会看到 new 在 ARC 上下文中的使用频率越来越高,看来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多