0

我在读取来自 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;

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

4

1 回答 1

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);
}
于 2013-02-28T07:10:22.093 回答