我遇到了来自 NSData 的非常奇怪的行为。当我尝试添加图像数据时,NSData var 莫名其妙地设置为 nil:
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
UIImage *i = [UIImage imageNamed:@"pic2"];
NSLog(@"image data %@", UIImagePNGRepresentation(i));
[postbody appendData:UIImagePNGRepresentation(i)];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *bodyString = [[NSString alloc] initWithData:postbody encoding:NSUTF8StringEncoding];
NSLog(@"body %@", bodyString);
上面记录图像数据显示 UIImagePNGRepresentation(i) 实际上是在返回数据,但是当记录正文时,日志显示为 nil。为什么会这样?