folder size wrong

↘锁芯ラ 提交于 2019-12-12 03:20:06

问题


This code is correct but the folder size is wrong. If I change the directory the size is always wrong. For example the size of "%@/Caches/com.apple.Safari/Webpage Previews" is 23 MB, but I have 16.5 KB.

NSString *path = [NSString stringWithFormat:@"%@/Caches/com.apple.Safari/Webpage Previews", [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    NSNumber *fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] objectForKey:NSFileSize];
    resultsize += [fileSize unsignedLongLongValue];

also I used this but the size is always wrong:

NSFileManager *fm = [[NSFileManager alloc] init];    
    NSURL *LibraryURL = [[fm URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *previewsURL = [LibraryURL URLByAppendingPathComponent:@"Caches/com.apple.Safari/Webpage Previews"];

    resultSize += [[[fm attributesOfItemAtPath:[previewsURL path] error:nil] objectForKey:NSFileSize] unsignedIntegerValue];

Can you help me? Thanks.


回答1:


If you want to get the size of all the files in a folder, you'll need to iterate through the contents of the folder and get the sizes of the actual files:

unsigned long long totalSize = 0;
NSFileManager *fm = [[NSFileManager alloc] init];
NSURL *libraryURL = [[fm URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *previewsURL = [LibraryURL URLByAppendingPathComponent:@"Caches/com.apple.Safari/Webpage Previews"];

NSDirectoryEnumerator *enumerator = [fm enumeratorAtURL:previewsURL includingPropertiesForKeys:[NSArray arrayWithObject:NSURLFileSizeKey] options:0 errorHandler:nil /* or an actual error handler */];

for (NSURL *url in enumerator) {
    NSNumber *sizeNumber;
    if ([url getResourceValue:&sizeNumber forKey:NSURLFileSizeKey error:nil /* or an error */])
        totalSize += [sizeNumber unsignedLongLongValue]; 
}

(I haven't tested this.)




回答2:


Lion has some kind of Cache for these cumulative sizes. Try on a server volume (Mac OS X Lion Server AFP):

  • Open a Folder with lots of Subfolders
  • Menu View > as List
  • Menu View > Arrange By > Size
  • Finder shows all subfolders in the "---" group
  • Menu View > Show View Options
  • check the box "Calculate all File Sizes"
  • now Finders groups the subfolders appropriately
  • and even when you close that window, disconnect server and connect again, these sizes are there faster and also when not arranged by size

-> where is this information stored? which API to use?



来源:https://stackoverflow.com/questions/9064791/folder-size-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!