应用程序在NSURLConnection中崩溃

时间:2012-06-18 14:08:25

标签: iphone objective-c cocoa crash nsurlconnection

我正在尝试使用像

这样的异步类型将URL发布到服务器
_urlConn = [[NSURLConnection alloc] initWithRequest:_urlReq delegate: self];

我得到了正确的响应,我正在使用诸如didRecieveResponse和connectionDidFinishLoading之类的委托方法来很好地处理响应。到目前为止流程工作正常。我正面临一个我无法清楚解决的新问题。

假设我有一个会发布相同网址的按钮。

  1. 我点击按钮发布网址
  2. 当再次按下按钮时(在一秒/两秒内),URL不会 发表(我写过逻辑)。
  3. 网址已发布(点击第一个按钮),我没有收到 到目前为止的任何回复,现在我想再次点击按钮 现在将发布URL。
  4. 我的应用程序正好在这里。是因为我在_ReleaseObject(_urlConn);方法????

    中使用connectionDidFinishLoading

2 个答案:

答案 0 :(得分:1)

使用委托回调时需要非常小心。

在此示例中,单个对象是两个同时NSURLConnection对象的委托。这是一个坏主意。除非您开发了一种将特定连接与相应的响应数据对象相关联的方法,否则最终会混合响应数据。在这种情况下,你通过使用_urlConn(我假设的iVar)而不是连接(传递给-connectionDidFinishLoading:的参数)让自己变得更糟。

为了简化所有这些,您需要在现有请求待处理时不要发出新请求,或者在开始新请求之前需要cancel旧请求。

答案 1 :(得分:1)

我刚回答somebody's question here关于使用同一代理处理多个并发下载的问题。 (@Jeffery是对的 - 它需要保持每个状态,键入连接对象)。

以下是我如何处理您的具体示例...

- (IBAction)postButtonPressed:(id)sender {

    sender.enabled = NO;  // no more presses until we are ready again

    [UIView animateWithDuration:0.3 animations:^{
        sender.alpha = 0.3;  // or some effect to make your button appear disabled
    }];

    NSURLRequest *request = // build your post request here

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
        completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

            // check for error, do whatever you intend with the response
            // then re-enable the button
            sender.enabled = YES;
            [UIView animateWithDuration:0.3 animations:^{sender.alpha=1.0;}];
    }];
}