我在实现NSURLConnection包装器时遇到了一些麻烦。我正在使用POST数据创建NSURLConnection,并且连接似乎接收响应以及数据。 didReceiveData回调记录responseData长度,即2000字节。但是,当didFinishLoading触发时,responseData包含0个字节。有关在哪里查找可能修改responseData内容的任何提示?它在didReceiveResponse中重置,但似乎没有在didReceiveData和didFinishLoading之间调用didReceiveResponse。
以下是日志中的一些输出:
当前语言:auto;目前客观-c 2012-01-24 13:35:40.020 PSIdea [24007:11903] didReceiveResponse:responseData length:(0)
警告:尝试使用块创建USE_BLOCK_IN_FRAME变量 那不在框架中。 2012-01-24 13:35:40.604 PSIdea [24007:11903] didReceiveData。 responseData length:(2233)2012-01-24 13:35:40.604 PSIdea [24007:11903] didFinishLoading:responseData length:(0)
2012-01-24 13:35:41.881 PSIdea [24007:11903] responseData as string:
2012-01-24 13:35:41.882 PSIdea [24007:11903] responseData as 词典:
以下是相关代码:
NetworkController.m
-(void)postRequestToURL:(NSURL*)url withData:(NSData*)data withContentType:(NSString*)contentType
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
if (!contentType)
{
contentType = @"application/x-www-form-urlencoded";
}
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:data];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)connection:(NSConnection*)conn didReceiveData:(NSData*)data
{
[_responseData appendData:data];
NSLog(@"didReceiveData. responseData length:(%d)", _responseData.length);
}
-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{
if (_responseData == NULL) {
_responseData = [[NSMutableData alloc] init];
}
[_responseData setLength:0];
NSLog(@"didReceiveResponse: responseData length:(%d)", _responseData.length);
}
-(void)connection:(NSConnection*)conn didFailWithError:(NSError *)error
{
NSLog([NSString stringWithFormat:@"Connection failed: %@", error.description]);
}
PSINetworkController.m(子类)
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(@"didFinishLoading: responseData length:(%d)", _responseData.length);
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData as string: %@", responseString);
SBJsonParser* parser = [[SBJsonParser alloc] init];
NSDictionary* dict = [parser objectWithData:_responseData];
NSLog(@"responseData as dictionary:");
for (id key in dict) {
NSLog(@"%@=%@", key, [dict objectForKey:key]);
}
[_delegate connection:connection receivedResponse:dict];
}
感谢。
编辑: 此外,我似乎偶然发现了一个解决方案。这个问题确实与声明_responseData的方式有关。
将响应数据声明为原子属性会导致响应数据像以前一样被重置。
@property (retain) NSMutableData* responseData;
然而,简单地在界面中声明变量似乎消除了这个问题 - 数据从didReceiveData持续到didFinishLoading。
@interface NetworkController : NSObject
{
NSMutableData* _responseData;
}
我的理解是,声明属性只会生成setter和getter,但我没有看到这种情况如何相关。谁能解释一下?
编辑:我忽略了提到这个项目正在使用ARC。