我正在使用Xcode构建一个Mac应用程序,它在其中一个方法中具有非常持久的循环。我在自动释放池(@autoreleasepool)中使用循环,但我的应用程序最终仍然没有内存。
我的应用程序在后台执行一个线程并使用运行系统范围文件搜索的NSDirectoryEnumerator并更改整个系统上每个文件的每个图标(使用NSWorkspace),并不断更新文件路径已更改的文本字段。这显然是为什么内存耗尽,但我想知道如何在不释放内存的情况下阻止它耗尽内存。
这是我的源代码:
NSImage *newFileIcon = ...;
NSImage *newFolderIcon = ...;
NSString *sourcePath = [@"/" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *directoryURL = [NSURL fileURLWithPath:sourcePath];
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
[[NSWorkspace sharedWorkspace] setIcon:newFolderIcon forFile:[directoryURL path] options:NSExcludeQuickDrawElementsIconCreationOption];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:directoryURL includingPropertiesForKeys:keys options:0 errorHandler:^(NSURL *url, NSError *error) {return YES;}];
@autoreleasepool {
for (NSURL *url in enumerator) {
NSError *error;
NSNumber *isDirectory = nil;
if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
NSLog(@"Error!"); // File Error
} else if (![isDirectory boolValue]) {
// Set File Icon
[[NSWorkspace sharedWorkspace] setIcon:newFileIcon forFile:[url path] options:NSExcludeQuickDrawElementsIconCreationOption];
// Update Status TextField
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self.statusField setStringValue:[NSString stringWithFormat:@"Changed File : \n%@", url.path]];});
// Log File Changed
NSLog(@"Changed File : %@", [url path]);
} else if ([isDirectory boolValue]) {
// Set Folder Icon
[[NSWorkspace sharedWorkspace] setIcon:newFolderIcon forFile:[url path] options:NSExcludeQuickDrawElementsIconCreationOption];
// Update Status TextField
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self.statusField setStringValue:[NSString stringWithFormat:@"Changed Folder : \n%@", url.path]];});
// Log Folder Changed
NSLog(@"Changed Folder : %@", [url path]);
}
}
}
由于