計算緩存大小泥耀。
在字符串分類中暴露兩個方法:1個是計算大小,1個是根據(jù)大小分類讥裤。
方法實現(xiàn)
- (NSInteger)fileSize
{
// 創(chuàng)建文件管理者
NSFileManager *manager = [NSFileManager defaultManager];
// 先判斷文件是否存在
BOOL isDirectory = NO;
BOOL exist = [manager fileExistsAtPath:self isDirectory:&isDirectory];
// 如果文件不存在
if (exist==NO) return 0;
// 如果文件存在? 判斷為文件夾還是文件
if (isDirectory) {
// 計算文件大小放棒。拿到了完整路徑
NSInteger fileSize = 0;
// 用完整路徑查詢所有的文件的大小,返回為數(shù)組
NSArray *pathArray = [manager subpathsAtPath:self];
// 遍歷數(shù)組,將獲得的數(shù)組字符串拼接到file上
for (NSString *path in pathArray) {
// 獲得完整地址
NSString *fulSubPath = [self stringByAppendingPathComponent:path];
// 獲得屬性
NSDictionary *attrs = [manager attributesOfItemAtPath:fulSubPath error:nil];
// 過濾掉文件夾
if ([attrs[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
// 將屬性中的fileSize相加。
fileSize += [attrs[NSFileSize] integerValue];
}
return fileSize;
}
return [[manager attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
}
- (NSString *)fileSizeString
{
NSInteger fileSize = self.fileSize;
// 設(shè)定一個單位
CGFloat unit = 1000.0;
// 對fileSize進行判斷
if (fileSize>= unit * unit * unit) {
return [NSString stringWithFormat:@"%.1fGB",fileSize/(unit*unit*unit)];
}else if (fileSize>= unit*unit) {
return [NSString stringWithFormat:@"%.1fMB",fileSize/(unit*unit)];
}else if (fileSize>= unit){
return [NSString stringWithFormat:@"%.1fKB",fileSize/unit];
}else
{
return [NSString stringWithFormat:@"%zdB",fileSize];
}
}