2010-10-18 54 views
1

我寫過的方法可以幫助我獲得文件/文件夾的大小,並將結果轉換爲可讀的字符串。問題是,當這個大小超過大約2.1GB時,返回的數字變成一個隨機的負數,比如「-4324234423 bytes」,這是無用的。FileSize問題 - 可可

事情我已經發現了約&做這個問題:

  • 32GB僅限於此大小,所以我在64位編譯代替。
  • 我試過使用CGFloat和NSUInteger,但兩者仍然返回與NSInteger相同的值。

我很沮喪,我不知道我在想什麼。這裏是我的方法:

- (NSString *)stringFromFileSize:(int)theSize 
{ 
CGFloat floatSize = theSize; 
if (theSize<1023) 
    return([NSString stringWithFormat:@"%i bytes",theSize]); 
floatSize = floatSize/1024; 
if (floatSize<1023) 
    return([NSString stringWithFormat:@"%1.1f KB",floatSize]); 
floatSize = floatSize/1024; 
if (floatSize<1023) 
    return([NSString stringWithFormat:@"%1.2f MB",floatSize]); 
floatSize = floatSize/1024; 

return([NSString stringWithFormat:@"%1.2f GB",floatSize]); 
} 

- (NSUInteger)sizeOfFile:(NSString *)path 
{ 
NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil]; 
NSUInteger fileSize = (NSUInteger)[fattrib fileSize]; 
return fileSize; 
} 

- (NSUInteger)sizeOfFolder:(NSString*)folderPath 
{ 
NSArray *contents; 
NSEnumerator *enumerator; 
NSString *path; 
contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath]; 
enumerator = [contents objectEnumerator]; 
NSUInteger fileSizeInt = 0; 
while (path = [enumerator nextObject]) { 
    NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:path] error:nil]; 
    fileSizeInt +=[fattrib fileSize]; 
} 
return fileSizeInt; 
} 

我在想什麼? NSFileManager是否返回32位值?這是什麼造成的?

謝謝!

回答

1

唉,即使您「爲64位編譯」,幾乎所有系統的「int」都是32位。 (Windows,Mac和Linux以這種方式工作)。見http://en.wikipedia.org/wiki/64-bit#Specific_C-language_data_models

您可以將long傳遞給您的stringFromFileSize方法,也可以傳遞NSUInteger

+0

我認爲CGFloat的是64位呢? – Pripyat 2010-10-18 16:25:17

+0

問題在於,在「stringFromFileSize」中創建「CGFloat」時,該值已經是「int」(該函數的參數),並且如果處理大值,因爲整數不能存儲大於2G的值(如果它們的簽名爲32位)。 – 2010-10-18 16:30:04

+0

啊我明白了!這是真的...... – Pripyat 2010-10-18 16:35:38

0

有點晚,但是你可以用用正確的數字格式這一行:

NSString *fileSizeStr = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleFile];