使用自定义的字符串函数代替ByteCountFormatter自带的函数
例如,用以下代码替换原来的ByteCountFormatter代码:
extension Int {
func fileSizeString() -> String {
let byteCount = Double(self)
let KB = byteCount / 1024.0
if KB < 1.0 { return "\(Int(byteCount))B" }
let MB = KB / 1024.0
if MB < 1.0 { return "\(KB.formattedToTwoDecimalPlaces)KB" }
let GB = MB / 1024.0
if GB < 1.0 { return "\(MB.formattedToTwoDecimalPlaces)MB" }
let TB = GB / 1024.0
if TB < 1.0 { return "\(GB.formattedToTwoDecimalPlaces)GB" }
let PB = TB / 1024.0
return "\(PB.formattedToTwoDecimalPlaces)TB"
}
}
extension Double {
var formattedToTwoDecimalPlaces: String {
return String(format: "%.2f", self)
}
}
然后使用如下方法获取文件大小字符串:
let fileSizeString = fileSize.fileSizeString()
其中,fileSize是文件大小的Int类型,fileSizeString是文件大小的字符串表示。这种方法避免了原有ByteCountFormatter的内存泄漏问题。