关于NSURLConnection的retainCount有点混乱 [英] been having a little confusion about the retainCount of NSURLConnection

查看:94
本文介绍了关于NSURLConnection的retainCount有点混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先看看这些代码:

NSURL *url = [[NSURL alloc] initWithString:@"lasdhfkjasf"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *_conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(@"aaaaaaaaa  %d", [_conn retainCount]);
[url release];
[request release];
[_conn release];

结果显示它打印aaaaaaaaaaaaaa 2,不应该是1吗?或者有某种然后我改变它:

turns out it prints "aaaaaaaaaaaaa 2",shouldn't it be 1?Or there are some kind of exception out there.Then I change it :

NSURL *url = [[NSURL alloc] initWithString:@"lasdhfkjasf"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *_conn = [[NSURLConnection alloc] init];
NSLog(@"aaaaaaaaa  %d", [_conn retainCount]);
[url release];
[request release];
[_conn release];

我不知道发生在initWithRequest:delegate:方法中,有人知道吗? / p>

I don't know happen in the initWithRequest:delegate: method,has anybody know about it?

推荐答案

这里的一切都绝对正确:NSURLConnection必须保留自己,以确保它可以向委托提供数据(并且这样做)它不能被解除分配)。如果没有委托,则没有人监听该连接,并且没有理由执行任何操作,因此它不会保留自己。 Connection然后在以下情况下释放:

Everything is absolutely OK here: NSURLConnection must retain itself to be sure that it can deliver data to the delegate (and to do that it must not be deallocated). If there is no delegate, then nobody listens to that connection and there is no reason to perform anything, so it doesn't retain itself. Connection then releases itself after:

-(void) connectionDidFinishLoading:(NSURLConnection*) connection

OR

-(void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error

来自你的例子:

. . .
NSURLConnection *_conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
. . .
[_conn release];

如果retainCount为1,则在 [_ conn release] 该对象将立即被释放,并且根本不会加载。

if retainCount was 1, then after [_conn release] the object would be deallocated immediately and there would be no loading at all.

对于所有人,他们说retainCount工作不正确:你就是不知道它是如何工作的。至于NSString'古怪':这不奇怪,这只是性能优化。 2147483647 retain count表示对象在内存中是常量(并在app终止时被删除)。这在编译期间已知值时完成:

To all of you, who says that retainCount works incorrectly: you just don't know how it works. As for NSString 'oddity': this is not oddity, this is just performance optimization. 2147483647 retain count means that object is constant in memory (and is deleted when app terminates). This is done when the value is known during compilation:

NSString* str = @"12345"; //has 2147483647 retain count.

这篇关于关于NSURLConnection的retainCount有点混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆