Ios NSMutableData initWithCapacity?
我有这些方法来处理下载 但初始化NSMutableData时出错Ios NSMutableData initWithCapacity?,ios,download,nsmutabledata,Ios,Download,Nsmutabledata,我有这些方法来处理下载 但初始化NSMutableData时出错 NSNumber *filesize; NSMutableData *data; - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { filesize = [NSNumber numberWithUnsignedInteger:[response expectedContentLen
NSNumber *filesize;
NSMutableData *data;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
filesize = [NSNumber numberWithUnsignedInteger:[response expectedContentLength]];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)recievedData {
if (data==nil) {
data = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
}
[data appendData:recievedData];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data length]]; //MAGIC
float progress = [resourceLength floatValue] / [filesize floatValue];
progressBar.progress = progress;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error "
message:@" " delegate:self cancelButtonTitle: @"OK"
otherButtonTitles:nil];
[alertView show];
connection1=nil;
[connection1 cancel];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
}
这里生成错误
data=[[NSMutableData alloc]initWithCapacity:[filesize floatValue]]强>
[nsContentEmulableData initWithCapacity::]:最大容量:4294967295,最大大小:2147483648字节
如果
nsurresponse expectedContentLength
不知道长度,它将返回-1(文档中说nsurresponseunknownlength
,这是一个初始化为-1的常量)
然后,您可以使用一种有趣的方式从long
(结果类型为nsurresponse expectedContentLength
)通过NSNumber numberwhithunsignedinteger
和NSNumber floatValue
到nsinteger
(参数到NSMutableData initWithCapacity:
)。结果是-1(内部表示为0xFFFFFF)最终为4294967295(内部表示为0xFFFFFF)
您必须测试
nsurresponseunknownlength
,并在这种情况下使用不同的初始容量。不要使用NSNumber
。只要将有符号的long-long
转换为无符号的NSUInteger
,如果它在合理的范围内。这不应该是initWithCapacity:[filesize unsignedIntValue]
?我尝试了,但仍然标记了相同的错误。我能做什么?看@Codo的彻底回答。