1

httpController.h 中的一些代码如下:

@interface httpController:NSObject{
  ...
  NSMutableData *receivedData;
}
@property (nonatomic,retain) NSMutableData *receivedData;

httpController.m 文件中的一些代码如下:

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

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data               
{
  if (!receivedData) {
      receivedData = [[NSMutableData alloc] init];
  }
  [receivedData appendData:data];  
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

}

然后我想在 main.m 文件中使用 receivedData,如下所示:

int main(int argc, const char *argv[])
{
   HttpController *httpController = [[HttpController alloc] init];
   NSURLRequest *request = ...;
   NSURLConnection *connetion = ...;
   if(connection)
   {
     NSMutableData *_receviedData = httpController.receivedData;
     NSString * dataString = [[[NSString alloc] initWithData:_receviedData encoding:NSUTF8StringEncoding] autorelease]; 
     NSLog(@"%@",dataString);
   }
   [[NSRunLoop currentRunLoop] run];
}

但是我发现在main()函数中,_receivedData的值是空的,并且有注释输出。任何人都可以告诉我有什么问题吗?

4

1 回答 1

1

+connectionWithRequest:delegate:异步运行。看起来它在返回之前没有完成连接,这就是你看不到任何数据的原因。改为尝试+sendSynchronousRequest:returningResponse:error:,因为这将阻塞线程,直到连接完成。

使用任何一个时都不需要 HttpController/delegate +sendSynchronousRequest:returningResponse:error:。这是如何做到的:

int main(int argc, const char *argv[])
{
    NSURL           *url        = [NSURL URLWithString:@"http://www.yahoo.com/"];
    NSURLRequest    *request    = [NSURLRequest requestWithURL:url];
    NSURLResponse   *response   = nil;
    NSError         *error      = nil;

    // This blocks "this" thread until it's done.
    NSData          *data       = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (!data)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
        NSLog(@"%@", dataString);
    }
}

If you don't want to block the thread, then +connectionWithRequest:delegate: is the way to go. But you'll have to write your code differently, and should read the docs.

于 2012-04-24T14:51:58.430 回答