我正在使用返回大量数据的NsUrlConnection调用Web服务。这是多次调用didReceiveData方法,当我打印出来时,NSLog显示数据是正确的。
我遇到的问题现在与将didReceiveData方法中返回的NSData存储到NSMutableData ivar以供以后使用有关。
我在http://cagt.bu.edu/w/images/8/8b/URL_Connection_example.txt找到了一个使用它的示例,并进行了一些修改,我已经得到以下内容:
·H
@property (nonatomic,assign) NSMutableData *receivedData;
的.m
@synthesize receivedData;
-(Boolean) getCategories {
MCUtility * util = [MCUtility alloc];
NSString * strUrl = [NSString stringWithFormat:@"%@", [util getCategoryUrl]];
NSLog(@"%@", [NSString stringWithFormat:@"%@", strUrl]);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection == nil) {
return FALSE;
} else {
self.receivedData = [NSMutableData data];
[receivedData setLength:0]; //<<OK call
}
return TRUE;
}
#pragma NSURLCONNECTION
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse object.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
if (receivedData != nil)
[receivedData setLength:0]; //<< thread EXC_BAD_ACCESS (code 2, address....)
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"Data Received");
NSLog(@"%@", [NSString stringWithFormat:@"%@", [NSString stringWithUTF8String:[data bytes]]]);
[receivedData appendData:data]; //<< (2) thread EXC_BAD_ACCESS (code 2, address....)
在设置方法getCategories中,我使用
创建初始NSMutableData变量self.receivedData = [NSMutableData data];
((1)在此之后我添加了对[receivedData setLength:0]的测试调用;这实际上并不是代码的一部分,但在这里工作正常。)
对Web服务的调用很好,所以我开始在didReceiveData中接收数据。
在方法didReceiveResponse中,该示例声明了对[receivedData setLength:0]的调用;是必须的。此时我现在得到了一个
thread EXC_BAD_ACCESS (code 2, address....)
..我没有&#39;在我之前创建iVar对象之后就像我在(1)
中所说的那样得到这个错误在方法didReceiveData中,当我尝试在(2)处将数据分配给NSMutableData时,我也收到此错误。
因此,作为一个客观的新手,我认为这与我用来存储数据的iVar有关。是否有任何简单明显的错过?
答案 0 :(得分:1)
receivedData
正在发布。
[NSMutableData data]
返回一个自动释放的变量。您需要保留它或更改属性定义以保留它。
@property (nonatomic,retain) NSMutableData *receivedData;
应该有用。
如果使用ARC,请将该属性设为
@property (nonatomic,strong) NSMutableData *receivedData;