【问题标题】:NSMutableData initWithCapacity absurd capacity?NSMutableData initWithCapacity 荒谬的容量?
【发布时间】:2013-08-21 18:55:36
【问题描述】:

我有这些处理下载的方法

但是初始化NSMutableData时出错

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]];

[NSConcreteMutableData initWithCapacity:]:荒谬容量:4294967295,最大大小:2147483648字节'

【问题讨论】:

  • 不应该是initWithCapacity:[filesize unsignedIntValue]吗?
  • 我尝试了,但我仍然标记了相同的错误。我能做什么?
  • 查看@Codo 的详尽回答。

标签: ios download nsmutabledata


【解决方案1】:

如果NSURLResponse expectedContentLength 不知道长度,它将返回-1(文档说NSURLResponseUnknownLength,这是一个初始化为-1 的常量)。

然后您使用一种有趣的方式从long longNSURLResponse expectedContentLength 的结果类型)通过NSNumber numberWithUnsignedIntegerNSNumber floatValueNSUInteger(到NSMutableData initWithCapacity: 的参数)。结果是 -1(内部表示为 0xffffffff)最终为 4294967295(内部也表示为 0xffffffff)。

您必须测试NSURLResponseUnknownLength 并在这种情况下使用不同的初始容量。并且不要使用NSNumber。如果在合理范围内,只需将有符号的long long 转换为无符号的NSUInteger

【讨论】: