Archive for the 'NSByteCountFormatter' Category

2015/04/02 CocoaでDisk Free Space (Bytes) を求める

Shane wrote me various methods to get free space in Cocoa way. NSByteCountFormatter seems very useful.

“usedSpaceLongString” is good because they take the user’s number formatting and language into account (Shane said).

ShaneがCocoaでDiskの空き容量を(Byte単位で)返すscriptを書いてくれました(Thanks!)。NSByteCountFormatterが非常に使い勝手がありそうです。

“usedSpaceLongString”は実行時のユーザー環境の数値フォーマット形式と言語設定を反映させるため有用です(Shane談)。

あれ??? このScript、使用率が%で返ってきているものをただ文字フォーマットしているだけかも、、、

AppleScript名:CocoaでDiskSpace(Bytes)を求める
– Created 2015-04-02 by Shane Stanley
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”

usedSpace(“/”)
–>  4.5772857344E+10

usedSpace2(“/”)
–>  4.5772857344E+10

usedSpaceString(“/”)
–>  ”45.77 GB”

usedSpaceLongString(“/”)
–>  ”45.77 GB (45,772,857,344 bytes)”–English user environment
–>  ”45.77 GB (45,772,857,344 バイト)”–Japanese user environment

tell application “Finder”
  free space of startup disk
end tell
–>  4.5784592712E+10

on usedSpace(volumePath)
  set theNSURL to current application’s class “NSURL”’s fileURLWithPath:volumePath –considering “ASOC in Xcode”
  
set {theResult, theSize} to theNSURL’s getResourceValue:(reference) forKey:(current application’s NSURLVolumeAvailableCapacityKey) |error|:(missing value)
  
  
return theSize as real – integer may be too big for AS
end usedSpace

on usedSpace2(volumePath)
  set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value)
  
  
return (fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize)) as real – integer may be too big for AS
end usedSpace2

on usedSpaceString(volumePath)
  set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value)
  
set fRes to fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize)
  
  
–Formatting
  
set sizeString to current application’s NSByteCountFormatter’s stringFromByteCount:fRes countStyle:(current application’s NSByteCountFormatterCountStyleDecimal)
  
  
return sizeString as text
end usedSpaceString

on usedSpaceLongString(volumePath)
  set fileAttr to current application’s NSFileManager’s defaultManager()’s attributesOfFileSystemForPath:volumePath |error|:(missing value)
  
set fRes to fileAttr’s objectForKey:(current application’s NSFileSystemFreeSize)
  
  
–Formatting
  
set theFormatter to current application’s NSByteCountFormatter’s alloc()’s init()
  
theFormatter’s setCountStyle:(current application’s NSByteCountFormatterCountStyleDecimal)
  
theFormatter’s setIncludesActualByteCount:true
  
set sizeString to theFormatter’s stringFromByteCount:fRes
  
  
return sizeString as text
end usedSpaceLongString

★Click Here to Open This Script