5
我將文件存儲在本地文檔目錄中,並按文件夾分隔。 有沒有一種簡單的方法來獲取文檔目錄和iPhone上所有子目錄的內容的文件大小?iOS遞歸文件夾大小
我可以手動迭代文件夾並不斷添加文件大小,但我希望有更清晰和更高效的東西。
謝謝!
我將文件存儲在本地文檔目錄中,並按文件夾分隔。 有沒有一種簡單的方法來獲取文檔目錄和iPhone上所有子目錄的內容的文件大小?iOS遞歸文件夾大小
我可以手動迭代文件夾並不斷添加文件大小,但我希望有更清晰和更高效的東西。
謝謝!
你可以遞歸遍歷所有的文件夾,並獲得大小。 像這樣:
+(NSUInteger)getDirectoryFileSize:(NSURL *)directoryUrl
{
NSUInteger result = 0;
NSArray *properties = [NSArray arrayWithObjects: NSURLLocalizedNameKey,
NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey, nil];
NSArray *array = [[NSFileManager defaultManager]
contentsOfDirectoryAtURL:directoryUrl
includingPropertiesForKeys:properties
options:(NSDirectoryEnumerationSkipsHiddenFiles)
error:nil];
for (NSURL *fileSystemItem in array) {
BOOL directory = NO;
[[NSFileManager defaultManager] fileExistsAtPath:[fileSystemItem path] isDirectory:&directory];
if (!directory) {
result += [[[[NSFileManager defaultManager] attributesOfItemAtPath:[fileSystemItem path] error:nil] objectForKey:NSFileSize] unsignedIntegerValue];
}
else {
result += [CacheManager getDirectoryFileSize:fileSystemItem];
}
}
return result;
}
方法和效率取決於iOS版本。對於iOS 4.0及更高版本,你可以做一個類別上NSFileManager
像這樣的東西:
- (unsigned long long)contentSizeOfDirectoryAtURL:(NSURL *)directoryURL
{
unsigned long long contentSize = 0;
NSDirectoryEnumerator *enumerator = [self enumeratorAtURL:directoryURL includingPropertiesForKeys:[NSArray arrayWithObject:NSURLFileSizeKey] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:NULL];
NSNumber *value = nil;
for (NSURL *itemURL in enumerator) {
if ([itemURL getResourceValue:&value forKey:NSURLFileSizeKey error:NULL]) {
contentSize += value.unsignedLongLongValue;
}
}
return contentSize;
}
計算一個目錄在磁盤上佔用的大小實際上會涉及更多一點。找出如何在[這個答案](http://stackoverflow.com/a/28660040/104790)到一個類似的問題。 –