5

我在 NSThread 中使用 NSURLConnection,但没有执行 NSURLConnection 的委托方法!我的 NSTread 子类中有一个 main 方法和一个保持线程处于活动状态的 while 循环。有什么帮助吗?

很抱歉所有这些代码,但我认为这是描述我的问题的最佳方式。所以这是一个执行异步连接调用的对象createConnectionWithPath:userObjectReference

@interface WSDAsyncURLConnection : NSObject 
{
    NSMutableData *receivedData;
    NSDate *connectionTime;
    NSURLConnection *connection;

    id _theUserObject;

}


@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSDate *connectionTime;
@property (nonatomic, assign) NSURLConnection *connection;

- (void)createConnectionWithPath:(NSString *)thePath userObjectReference:(id)userObject;


@end


#import "WSDAsyncURLConnection.h"

@implementation WSDAsyncURLConnection
@synthesize connectionTime, receivedData, connection;


- (void) terminate
{
    if (self.connection) {
        [self.connection release];
        self.connection = nil;
    }
}   


- (void) createConnectionWithPath:(NSString *)thePath userObjectReference:(id)userObject;
{   
    _theUserObject = userObject;


    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:thePath]
                                                cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];


    self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

    if (self.connection) 
    {
        /* record the start time of the connection */
        self.connectionTime = [NSDate date];

        /* create an object to hold the received data */
        self.receivedData = [NSMutableData data];
    } 
}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.receivedData setLength:0];   
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    /* appends the new data to the received data */ 
    [self.receivedData appendData:data];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{    
    [self terminate];
}


- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    // displays the elapsed time in milliseconds
    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:self.connectionTime];
    // displayes the length of data received
    NSUInteger length = [self.receivedData length];

    NSString* aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];   

    [self terminate];


    [[NSNotificationCenter defaultCenter] postNotificationName:WSDAsynchURLConnectionDidFinished
                                                        object:_theUserObject 
                                                      userInfo:[NSDictionary dictionaryWithObject:aStr forKey:@"urlResponseString"]];

    NSLog(@"ti=%f, l=%d, response=%@", elapsedTime, length, aStr);

}

@end

这段代码主要来自苹果的示例项目,它在 NSThread 之外运行良好。但是当我在下面的线程子类中使用它时,没有执行委托方法!

@implementation IncomingThread



- (void) main {

    NSAutoreleasePool *poool = [[NSAutoreleasePool alloc] init];


// I start the URLConnection here ... But no delegate is executed !
        [urlConn createConnectionWithPath:@"http://localhost:8888" userObjectReference:nil];


    while (![self isCancelled]) {

        [NSThread sleepForTimeInterval:3.];
    }


    [poool release];

}


- (id) init
{
    self = [super init];
    if (self != nil) {

        urlConn = [[WSDAsyncURLConnection alloc] init];
    }
    return self;
}


- (void) dealloc {

    NSLog(@"deallocating (%@)...", [self className]);


    [urlConn release];

    [super dealloc];
}
4

4 回答 4

3

首先:您不需要在单独的线程中使用 NSURLConnection 。由于它是异步的,因此不会阻塞主线程。第二:没有处理你的连接,因为你总是用这种和平的代码停止线程的运行循环的执行:

 while (![self isCancelled]) {
        [NSThread sleepForTimeInterval:3.];
    }

从文档中sleepForTimeInterval

No run loop processing occurs while the thread is blocked.
于 2011-02-22T18:38:02.400 回答
1

你这样做很难。NSURLConnection不能很好地处理线程,因为它需要一个运行循环才能工作。您的线程没有运行循环,因此代码不起作用。为什么不在主线程上运行连接?或者,您可以将连接包装在此处的NSOperation示例代码中。现在,您还可以选择使用同步连接并将其分派到全局 GCD 队列。

于 2011-02-22T18:37:56.723 回答
0

你记得分配代表吗?

就像是:

self.connection.delegate = self;

仅仅因为您的类WSDAsyncURLConnection实现了委托方法,并不意味着它们被调用。

于 2011-02-22T18:55:00.353 回答
0

晚了,但它可能会挽救他人的生命:)

解决方案链接是:NSURLConnection 委托方法不起作用

于 2011-05-18T11:00:31.767 回答