Xcode NSURLConnection NSMutableData appdendData有时只能工作

时间:2013-02-28 07:03:38

标签: ios objective-c nsurlconnection nsmutabledata

我在阅读api的回复时遇到了一个奇怪的问题。在connectionDidFinishLoading中,将响应记录为字符串[NSString stringWithUTF8String:[self.response bytes]]时,字符串有时会被正确记录,有时会为空,其他时候是正确的响应,并在末尾附加随机字符。

在didReceiveData中,响应很好,但使用appendData后会出现问题。在didReceiveData中,我可以说明这样的问题:

// This is always 0
NSLog(@"data length is %i", [data length]);
// This is always the correct response string sent from the api
NSLog(@"data string is %@", [NSString stringWithUTF8String:[data bytes]]);

NSMutableData *foo = [[NSMutableData alloc] init];
[foo appendData:data];

// This is always 8
NSLog(@"foo length is %i", [foo length]);
// This is only sometimes the correct response string!
NSLog(@"foo string is %@", [NSString stringWithUTF8String:[foo bytes]]);

[foo release];
foo = nil;

关于appendData类似的疯狂问题,我已经看到了其他几个问题,但它们似乎是因为附加的变量是nil。这表明我已经清楚地声明了我的NSMutableData foo,但它仍未正确设置。

1 个答案:

答案 0 :(得分:2)

请发布整个代码,而不仅仅是这个简短的摘录。

我假设您每次调用NSMutableData时都会重新分配新的-connection:didReceiveData:实例。您需要使用属性或iVar,以便在后续调用-connection:didReceiveData:时将数据附加到现有数据。

- (void)startConnection
{
    self.receivedData = [[NSMutableData alloc] init];
    // Start connection...
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)
{
    NSString *receivedString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
    self.receivedData = nil;

    NSLog(@"Response: %@", receivedString);
}