代码之家  ›  专栏  ›  技术社区  ›  Rits

如何创建类似NSURLConnection的内容?

  •  0
  • Rits  · 技术社区  · 15 年前
    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 当运行循环完成并且自动释放池被排出时,保持活动状态,并确保 连接 在完成加载时释放。换句话说,我不知道如何复制 NSURLConnection公司 .

    2 回复  |  直到 15 年前
        1
  •  2
  •   JeremyP    15 年前

    无论出于何种目的,从外部来看,NSURLConnection都有效地保留了自己。这不是通过发送

    [self retain];
    

    启动连接时,然后

    [self release];
    

    其实你不必这么做。NSURLConnection保留其委托,因此JSON连接类应该创建一个NSURLConnection,将其自身作为NSURLConnection的委托传递。这样它的寿命至少和NSURLConnection一样长。它应该将JSON解析为方法中的字典 -connectionDidFinishLoading:

        2
  •  0
  •   Yuras    15 年前

    无论如何,应该有人追踪连接的实时性。在连接内部跟踪它是一个糟糕的解决方案。

    我认为正确的方法是使用singleton类来执行连接

    @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];
    }