Objective c 使用NSDirectoryEnumerator枚举根文件夹时CPU百分比变高
我正在使用NSDirectoryEnumerator枚举文件夹,但问题是,在枚举完成之前,CPU百分比增加了50%以上。是否有办法处理此问题Objective c 使用NSDirectoryEnumerator枚举根文件夹时CPU百分比变高,objective-c,macos,cocoa,Objective C,Macos,Cocoa,我正在使用NSDirectoryEnumerator枚举文件夹,但问题是,在枚举完成之前,CPU百分比增加了50%以上。是否有办法处理此问题 -(void)enumerateFolder:(NSString *)folder{ NSURL *directoryURL = [NSURL fileURLWithPath:folder]; NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
-(void)enumerateFolder:(NSString *)folder{
NSURL *directoryURL = [NSURL fileURLWithPath:folder];
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
NSInteger fileCount = 0;
NSInteger folderCount = 0;
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager]
enumeratorAtURL:directoryURL
includingPropertiesForKeys:keys
options:0
errorHandler:^BOOL(NSURL *url, NSError *error) {
// Handle the error.
// Return YES if the enumeration should continue after the error.
return YES;
}];
for (NSURL *url in enumerator)
{
NSError *error;
NSNumber *isDirectory = nil;
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
// handle error
}
else if (! [isDirectory boolValue]) {
// No error and it’s not a directory; do something with the file
fileCount++;
}else if([isDirectory boolValue]){
folderCount++;
}
}
}
您可能应该在后台线程中运行该API。您是否知道该API会扫描包括所有子文件夹在内的文件夹?@Sulthan它在后台线程中运行only@vardian是的,我知道。嗯,代码要求你的计算机做一些事情;在完成之前,它将使用CPU。不清楚你想要什么样的答案。我想你可以让你的循环每次都调用sleep(),这样它需要更长的时间,但占用更少的CPU。。。?这就是你要找的吗?