2

我想创建一个类来处理其他类的所有 HTTP 连接工作(以避免重复编写代码)。我称它为 ConnectionCenter(NSObject 的子类)并向其添加以下代码:

-(void)connect:(NSString *)strURL obj:(ConnectCenter *)objConnect
{
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:objConnect];
    if (theConnection) 
    {
        // receivedData is declared as a method instance elsewhere
        receivedData = [[NSMutableData data] retain];
    } 
    else 
    { 
        // inform the user that the download could not be made
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}

其他类通过传递 URL 和 ConnectionCenter 对象来调用它。但是没有调用 ConnectionCenter 中的方法“didReceiveData”。关于它有什么问题的任何想法?

4

2 回答 2

2

您需要[theConnection setDelegate:self]在设置连接后调用,因为connection:didReceiveData:它是一个委托方法。

阅读文档以获取更多信息。

于 2009-03-10T03:02:54.553 回答
0

关于这段代码的一些事情......

首先,令人困惑的是您实际上将哪个对象设置为委托。对 connection:didReceiveData: 的调用将在连接的委托上调用,它是您传递给 connect:obj: 方法的任何对象。您在 ConnectionCenter 上有一个实例方法,可以启动与不同 ConnectionCenter 对象作为委托的连接,这似乎很奇怪。确保您正在查看正确对象上的 connection:didReceiveData: 方法。

如果您没有收到任何数据,则您的连接可能无法连接或只是完成而没有返回任何数据。您应该实现 connectionDidFinishLoading: 和 connection:didFailWithError: 委托方法,以便您知道连接是否已完成,无论是否返回数据。

最后,如果你得到一个良好、快速的连接,你就会遇到一个竞争条件。NSURLConnection 对象将在您创建后立即开始运行。如果有任何数据要读取,它将调用 connection:didReceiveData: 并将其附加到 receivedData。但是,如果连接速度足够快,您最终可能会尝试将数据附加到尚未创建的 receivedData 上。这是一个很小的机会,但是即使 NSURLConnection 的 init 方法没有阻塞,在返回之前对它进行多少工作以使连接继续进行任何假设都是不明智的。在开始连接之前创建 receivedData 以便您可以确保在数据进入时有一个放置数据的地方。

于 2009-03-10T15:59:00.193 回答