【问题标题】:How to release NSURLConnection in iPhone(Objective C)如何在 iPhone 中释放 NSURLConnection(目标 C)
【发布时间】:2011-04-14 10:32:26
【问题描述】:

我在项目的很多地方都在各种功能下使用过这行代码:

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate:self];

现在我收到一个常见的警告“未使用的变量 theConnection”。 我也知道它的内存泄漏。

可以使用下面的代码吗?

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate:self];
[theConnection release];

如果我释放 Connection 对象,didReceiveData、connectionDidFinishLoading 等委托方法会出现问题吗?

如果上述语句可以毫无问题地解决内存泄漏,如何摆脱警告“未使用的变量等等等等”?

【问题讨论】:

    标签: iphone objective-c nsurlconnection


    【解决方案1】:
    Now I'm getting an usual warning "Unused variable theConnection". I also know that its leaking memory.
    

    因为您没有使用theConnection 对象而收到警告的原因,

    如果您不想为此实例调用 delgate 函数,请将您的 delegate 设置为 nil 而不是 self

    [[NSURLConnection alloc] initWithRequest:request delegate:nil];
    

    已编辑:

    在您的 .h 类中:

    NSURLConnection* m_URLConnection;
    

    在 .m 类中:

    -(id) init
    {
      m_URLConnection = [[NSURLConnection alloc] initWithRequest:request delegate:nil];
    }
    -(void) dealloc
    {
      [m_URLConnection release];
      m_URLConnection = nil ;
    }
    

    【讨论】:

    • 嘿,我要召集代表! :) 我现在该怎么办?
    • 感谢您更新的答案,但我已经多次使用我的代码行,几乎不可能更改完整的代码结构。如果您能提供一个我不需要更改代码结构的解决方案,将不胜感激。 :)
    【解决方案2】:

    我觉得你可以用这个

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    

    我认为这不会显示警告

    或者我认为您也可以尝试将连接对象作为类的实例变量。

    theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate:self];
    

    您可以根据dealloc 中的代码或其他方法发布theConnection 来避免泄漏

    【讨论】:

    • 这一行是否:'[[NSURLConnection alloc] initWithRequest:request delegate:self];'不会泄露内存?
    • 是的,这就是为什么我在回答中给了你另一个选项
    • 如果我使用[[NSURLConnection alloc] initWithRequest:request delegate:self]; 而不是NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate:self]; 然后使用分析器我会收到关于潜在内存泄漏的警告。 :(
    • 是的,您会遇到内存泄漏,这就是为什么我为您提供了使其成为 iVar 的选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多