2013-08-21 64 views
1

我有這些方法來處理下載NSMutableData initWithCapacity荒謬能力?

但是存在當初始化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 { 

} 

在這裏產生的誤差的誤差

數據= [[NSMutableData的alloc] initWithCapacity:[文件大小的floatValue] ]。

[NSConcreteMutableData initWithCapacity:]:荒謬的能力:4294967295,最大尺寸:2147483648個字節

+0

不應該是'initWithCapacity:[filesize unsignedIntValue]'? –

+0

我嘗試,但我仍然標記相同的錯誤。我可以做什麼? – Fabio

+0

查看@科多的徹底答案。 –

回答

2

如果NSURLResponse expectedContentLength不知道的長度,它會返回-1(文件說NSURLResponseUnknownLength,它是一個常量,初始化爲-1)。

然後,您使用一個有趣的方式來通過NSNumber numberWithUnsignedIntegerNSNumber floatValuelong long(結果類型的NSURLResponse expectedContentLength)去NSUInteger(參數NSMutableData initWithCapacity:)。結果是-1(內部表示爲0xffffffff)最終爲4294967295(內部也表示爲0xffffffff)。

在這種情況下,您必須測試NSURLResponseUnknownLength並使用不同的初始容量。並且不要使用NSNumber。如果在合理的範圍內,只需將已簽名的long long轉換爲未簽名的NSUInteger即可。