2011-04-14 80 views
0

我下各种功能使用此行代码在我的项目的许多地方iPhone(目标C):如何释放NSURLConnection的在

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

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

可以使用下面的代码吗?

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

如果我释放连接对象,会在didReceiveData,connectionDidFinishLoading等委托方法中出现问题吗?

如果上面的语句可以解决内存泄漏没有问题如何摆脱警告“未使用变量等等等等。”?

回答

0

我认为你可以使用这个

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

我不认为这会显示警告

或者我认为你也可以尝试进行连接对象的类的实例变量。

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

可避免释放theConnectiondealloc泄漏根据您的代码或其他方法

+0

请问这行:“[[NSURLConnection的alloc] initWithRequest:请求委托:自];' 不泄漏内存? – necixy 2011-04-14 11:03:21

+0

是这就是为什么我给你我的回答中的另一个选项 – visakh7 2011-04-14 11:12:59

+0

如果我使用'[[NSURLConnection alloc] initWithRequest:request delegate:self];'而不是'NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self] ;'然后使用分析仪我得到有关潜在的内存泄漏的警告。 :( – necixy 2011-04-14 12:01:07

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 ; 
} 
+0

嘿,我想被称为代表! :) 我应该怎么办? – necixy 2011-04-14 10:53:27

+0

@Guru:检查我更新的答案... – Jhaliya 2011-04-14 11:08:09

+0

感谢您的更新答案,但我已经使用过很多次我的代码行,几乎不可能更改完整的代码结构。 如果您可以提供不需要更改代码结构的解决方案,将不胜感激。 :) – necixy 2011-04-14 11:59:40