gpt4 book ai didi

objective-c - Cocoa NSBrowser 和 CFURLEnumeratorCreateDirectoryURL

转载 作者:行者123 更新时间:2023-12-03 17:58:38 25 4
gpt4 key购买 nike

我试图理解 Apple“ComplexBrowser”中的示例,但很难找到“CFURLEnumeratorCreateDirectoryURL”的任何 Material /教程。

ComplexBrowser Sample from Apple

这段代码到底发生了什么?

我不明白这种使用 CFURLEnumeratorGetNextURL 等循环的方式。

对我来说,使用 NSFileManager 的方法似乎更简单,但更有限?

NSArray *contentsAtPath = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:parentPath error:NULL];

- (NSArray *)children {
if (_children == nil || _childrenDirty) {
// This logic keeps the same pointers around, if possible.
NSMutableArray *newChildren = [NSMutableArray array];

CFURLEnumeratorRef enumerator = CFURLEnumeratorCreateForDirectoryURL(NULL, (CFURLRef) _url, kCFURLEnumeratorSkipInvisibles, (CFArrayRef) [NSArray array]);
NSURL *childURL = nil;
CFURLEnumeratorResult enumeratorResult;
do {
enumeratorResult = CFURLEnumeratorGetNextURL(enumerator, (CFURLRef *) &childURL, NULL);
if (enumeratorResult == kCFURLEnumeratorSuccess) {
FileSystemNode *node = [[[FileSystemNode alloc] initWithURL:childURL] autorelease];
if (_children != nil) {
NSInteger oldIndex = [_children indexOfObject:childURL];
if (oldIndex != NSNotFound) {
// Use the same pointer value, if possible
node = [_children objectAtIndex:oldIndex];
}
}
[newChildren addObject:node];
} else if (enumeratorResult == kCFURLEnumeratorError) {
// A possible enhancement would be to present error-based items to the user.
}
} while (enumeratorResult != kCFURLEnumeratorEnd);

[_children release];
_childrenDirty = NO;
// Now sort them
_children = [[newChildren sortedArrayUsingComparator:^(id obj1, id obj2) {
NSString *objName = [obj1 displayName];
NSString *obj2Name = [obj2 displayName];
NSComparisonResult result = [objName compare:obj2Name options:NSNumericSearch | NSCaseInsensitiveSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch range:NSMakeRange(0, [objName length]) locale:[NSLocale currentLocale]];
return result;
}] retain];
}

return _children;

}

最佳答案

由于此信息存储在不透明的 C 数据类型中,因此在核心基础中,它们提供了 C 例程来为您提供有关数据的信息。这是一种封装形式,以便他们可以在幕后更改内容,而不会影响库的公共(public)接口(interface)。

基本上,他们创建一个循环并不断询问目录中的下一个 URL,直到找到目录的末尾。

  • 枚举器是一种索引,用于跟踪它们在 URL 列表中的位置。
  • enumeratorResult 告诉我们是否获得了新的 URL(或者是一个错误,或者我们处于最后一条记录)。

当它遍历每个 URL 时,它会创建 FileSystemNode 并将它们添加到一个数组中,然后在循环遍历目录中的所有 URL 后返回该数组。

关于objective-c - Cocoa NSBrowser 和 CFURLEnumeratorCreateDirectoryURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9914203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com