0

我正在使用这段代码来获取文件夹 pathTo_Folder 中包含的文件。我得到的是这样的:“file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Tech-2.jpg”,“file://localhost/Users/ronny/DEV /0200-ObjC4/ModernTimes/DrawingFun/linen/Tech-3.jpg", "文件://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Tech-4.jpg", "文件://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-1.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen /Terra-2.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-3.jpg", "file://localhost/Users/ronny/DEV /0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-4.png", "文件:

我想知道是否有一种方法可以只获取文件名而不包含像“Tech-2.jpg”这样的文件夹

NSString *pathTo_Folder = @"/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen";

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *theFiles =  [fileManager contentsOfDirectoryAtURL:
                      [NSURL fileURLWithPath:pathTo_Folder]
                                includingPropertiesForKeys:[NSArray arrayWithObject:NSURLNameKey]
                                                   options:NSDirectoryEnumerationSkipsHiddenFiles
                                                     error:nil];

来自瑞士的问候,罗纳德霍夫曼

4

2 回答 2

5
for( NSURL* fileURL in theFiles ) {
  NSString* filename = [fileURL lastPathComponent];
  // do things with the filename
}

根据评论,如果您只想要文件名:

// Note, this is not very efficient, and it's especially inefficient if
// you then go ahead and iterate the resultant array
NSArray* filenames = [theFiles valueForKeyPath:@"lastPathComponent"];
于 2012-10-16T02:48:12.863 回答
1

NSURL 有一个方法lastPathComponent可以完全满足您的需求。

于 2012-10-16T02:48:04.610 回答