Ios NSDirectoryEnumerator迭代元素可以';不比较后缀
我正在使用Ios NSDirectoryEnumerator迭代元素可以';不比较后缀,ios,objective-c,file,Ios,Objective C,File,我正在使用NSDirectoryEnmerator查找后缀为png和jpg的所有文件,后缀代码如下: NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:containerURL includingPropertiesForKeys:[NSArray array] options:0 errorHandler:^BOOL(NSURL *url, NSError *
NSDirectoryEnmerator
查找后缀为png
和jpg
的所有文件,后缀代码如下:
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:containerURL includingPropertiesForKeys:[NSArray array] options:0 errorHandler:^BOOL(NSURL *url, NSError *error) {
// handle error
return NO;
}];
NSString *fileOrDirectory = nil;
while ((fileOrDirectory = [directoryEnumerator nextObject])) {
if([fileOrDirectory hasSuffix:@".jpg"] || [fileOrDirectory hasSuffix:@".png"]){
NSLog(@" find a image file %@", fileOrDirectory );
}
}
但是有一个错误说,NSURL
没有方法hasSuffix
发生了什么以及如何使这项工作?迭代元素的类型到底是什么?上面的代码经常被认为是
NSString
,但它不能工作EnumeratorUrl方法使用NSURL
对象,而不是字符串(异常原因清楚地揭示了这一点),您只需比较路径扩展即可:
if ([fileOrDirectory.pathExtension isEqualToString:@"jpg"] ||
[fileOrDirectory.pathExtension isEqualToString:@"png"]) { ...
根据错误:[directoryEnumerator nextObject]
返回一个NSURL
对象,而不是NSString
对象。将fileOrDirectory=[directoryEnumerator nextObject]
替换为fileOrDirectory=[directoryEnumerator nextObject].absoluteString
?链接答案的区别是EnumeratorURL:
与EnumartorPath:
我想,这就解释了不同之处。@Larme我在互联网上发现了大量使用NSString
,它们都是错误的和误导性的吗?对不起,我编辑了我以前的评论:链接答案的差异是EnumeratorUrl:vs EnumeratorPath:我猜,这解释了返回的对象的不同类别