【问题标题】:How to create something like NSURLConnection?如何创建类似 NSURLConnection 的东西?
【发布时间】:2010-11-06 17:36:25
【问题描述】:
NSURL *URL = [NSURL URLWithString:@"http://www.stackoverflow.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

使用如此简单的代码,我可以在我的应用程序中加载网页。我不必担心保留或释放NSURLConnection,它会在加载完成后自动释放。

我正在围绕 NSURLConnection,JSONConnection 创建某种包装器。它允许我从网页加载 JSON 值并自动将其解析为 NSDictionary。现在,我必须像这样使用它:

JSONConnection *tempJSONConnection = [[JSONConnection alloc] initWithURLString:@"http://www.stackoverflow.com" delegate:self];
self.JSONConnection = tempJSONConnection;
[tempJSONConnection release];

然后,加载完成后,我调用self.JSONConnection = nil;

我想要的是这样做:

JSONConnection *connection = [JSONConnection connectionWithURLString:@"http://www.stackoverflow.com" delegate:self];

我知道如何创建这个方法。我只是不知道如何在运行循环完成并且自动释放池耗尽时保持connection 活着,并确保在完成加载时释放connection。换句话说,我不会复制NSURLConnection 的确切行为。

【问题讨论】:

  • 只是一个历史记录。多年来,传统上这是使用allseeing-i.com/ASIHTTPRequest 完成的!但是多年来(大约从 2012 年开始??)图书馆已经消失了。它是目前最好的图书馆之一,为行业提供了良好的服务。

标签: iphone objective-c cocoa-touch ios nsurlconnection


【解决方案1】:

对于所有意图和目的,从外部来看,NSURLConnection 有效地保留了自己。这可以通过发送

[self retain];

开始连接时,然后

[self release];

完成并通知代表后;或者它是通过将自己置于当前打开的连接池中并在完成时将其从该池中删除来完成的。

您实际上不必执行任何这些操作。 NSURLConnection 保留了它的委托,所以你的 JSON 连接类应该创建一个 NSURLConnection 作为 NSURLConnection 的委托传递。这样,它的寿命至少与 NSURLConnection 一样长。它应该将 JSON 解析为方法 -connectionDidFinishLoading: 中的字典,并在返回之前将字典传递给它的委托。返回后 NSURLConnection 将释放并可能释放自身并释放您的 JSON 连接。

【讨论】:

    【解决方案2】:

    在任何情况下都应该有人跟踪连接的实时时间。在连接内部跟踪它是一个不好的解决方案。

    IMO 正确的做法是使用单例类来执行连接

    @protocol JSONDataProviderDelegate <NSObject>
    - (void) JSONProvider:(JSONDataProvider*) provider didLoadJSON:(JSONObject*) object;
    - (void) JSONProvider:(JSONDataProvider*) provider didFainWithError:(NSError*) error;
    @end
    
    @interface JSONDataProvider : NSObject
    
    + (void) provideJSON:(NSURL*) url delegate:(id<JSONDataProviderDelegate>) delegate;
    + (void) removeDelegate:(id<JSONDataProviderDelegate>delegate);
    
    @end
    

    用法:

    - (void) onSomeEvent
    {
      [JSONDataProvider provideJSON:[NSURL URLWithString:@"http://example.com/test.json"] delegate:self];
    }
    
    - (void) JSONProvider:(JSONDataProvider*) provider didLoadJSON:(JSONObject*) object
    {
      NSLog(@"JSON loaded: %@", object);
    }
     - (void) dealloc
    {
      [JSONDataProvider removeDelegate:self];
      [super dealloc];
    }
    

    【讨论】:

    猜你喜欢
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多