2012-04-10 5 views
1

NSFileSystemFreeSizeの結果を利用可能なmb/gbのユーザフレンドリな文字列に変換するルーチンを持っている人はいませんか?私はそれの要点を持っていると思ったが、私は奇妙な結果を得ている。甘いNSFileSystemFreeSize:結果をmb/gbのユーザーフレンドリーな表示に変換しますか?

- (NSString*)getFreeSpace 
{ 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSDictionary* fileAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:documentsDirectory error:NULL]; 
unsigned long long freeSpaceInBytes = [[fileAttributes objectForKey:NSFileSystemFreeSize] unsignedLongLongValue]; 

NSString * space = [NSString stringWithFormat:@"Free Space: %fll", freeSpaceInBytes /1024./1024. /1024.]; 

NSLog(@"freeSpaceInBytes %llull %fll", freeSpaceInBytes, freeSpaceInBytes /1024./1024. /1024.); 

return space; 
} 

答えて

6
static NSString* prettyBytes(uint64_t numBytes) 
{ 
    uint64_t const scale = 1024; 
    char const * abbrevs[] = { "EB", "PB", "TB", "GB", "MB", "KB", "Bytes" }; 
    size_t numAbbrevs = sizeof(abbrevs)/sizeof(abbrevs[0]); 
    uint64_t maximum = powl(scale, numAbbrevs-1); 
    for (size_t i = 0; i < numAbbrevs-1; ++i) { 
     if (numBytes > maximum) { 
      return [NSString stringWithFormat:@"%.4f %s", numBytes/(double)maximum, abbrevs[i]]; 
     } 
     maximum /= scale; 
    } 
    return [NSString stringWithFormat:@"%u Bytes", (unsigned)numBytes]; 
} 
+0

!ありがとうございました。私は決してエレガントなものを思いついたことはありません。 –

+0

ねえ、私はobjective-cに新しいです。私はこのNSStringをどのように記録できるのでしょうか? NSLog(@ "%@"、prettyBytes);は動作していません 'Formatは 'id'型を指定しますが、引数は 'NSString *(*)(uint64_t)' '型です。 – iDev

+0

あなたはそれ自身に関数を送信しています。あなたは何かでそれを呼び出す必要があります... NSLog(@ "%@"、prettyBytes(someNumberOfBytes)) ' –

関連する問題