some codes in httpController.h like this:
@interface httpController:NSObject{
...
NSMutableData *receivedData;
}
@property (nonatomic,retain) NSMutableData *receivedData;
and some codes in httpController.m file like this:
@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 {
}
Then I want using the receivedData in the main.m file, like this:
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];
}
But i found that in the main() function, the value of _receivedData is empty, and there is noting outputted. Anyone can tell me What’s wrong about it?
+connectionWithRequest:delegate:runs asynchronously. It looks like it’s not finishing the connection before returning, which is why you don’t see any data. Try+sendSynchronousRequest:returningResponse:error:instead, as this will block the thread until the connection finishes.There’s no need for a HttpController/delegate when using
+sendSynchronousRequest:returningResponse:error:either. Here’s how to do it: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.