在 Objective-C 中检查目录中项目的属性

发布于 2024-10-16 06:57:14 字数 1637 浏览 5 评论 0原文

我编写了这段小代码来检查给定目录中有多少个子目录。它只检查第一级,有什么办法可以让它更简单吗?我添加了评论,也许更容易理解我的意图。谢谢你!

<前><代码> #import <基金会/Foundation.h> int main (int argc, const char * argv[]){
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];



// insert code here...
NSFileManager *filemgr;
NSMutableArray *listOfFiles;
NSDictionary *listOfFolders;
NSDictionary *controllDir;
int i, count;
NSString *myPath;

filemgr = [NSFileManager defaultManager];

myPath = @"/";

// list the files in the given directory (myPath)

listOfFiles = [filemgr directoryContentsAtPath: myPath];

// count the number of elements in the array
count = [listOfFiles count];

// check them one by one
for (i = 0; i < count; i++)
{
    // I need the full path
   NSString *filePath =[NSString stringWithFormat:@"%@/%@", myPath, [listOfFiles objectAtIndex: i]];

    // add every item with its attributes
    listOfFolders = [filemgr attributesOfItemAtPath:filePath error:NULL];

    // to avoid typo get the attribute and create a string
    controllDir = [filemgr attributesOfItemAtPath:@"/" error:NULL];
    NSString *toCheck = [NSString stringWithFormat:@"%@", [controllDir objectForKey:NSFileType]];   

    // the folder elements one by one
    NSString *fileType = [NSString stringWithFormat:@"%@", [listOfFolders objectForKey:NSFileType]];    


    if([toCheck isEqualToString:fileType])
        {
            NSLog(@"NAME: %@  TYPE: %@" ,[listOfFiles objectAtIndex:i],[listOfFolders objectForKey:NSFileType]);
        }                
}            

[pool drain];
return 0;
}

I have made this little code to check how many subdirectories are in a given directory. It checks only the first level, is there anyway I can make it simplier? I have added comments, maybe easier to understand my intention. Thank you!

    #import < Foundation/Foundation.h >            
            int main (int argc, const char * argv[]){
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];



// insert code here...
NSFileManager *filemgr;
NSMutableArray *listOfFiles;
NSDictionary *listOfFolders;
NSDictionary *controllDir;
int i, count;
NSString *myPath;

filemgr = [NSFileManager defaultManager];

myPath = @"/";

// list the files in the given directory (myPath)

listOfFiles = [filemgr directoryContentsAtPath: myPath];

// count the number of elements in the array
count = [listOfFiles count];

// check them one by one
for (i = 0; i < count; i++)
{
    // I need the full path
   NSString *filePath =[NSString stringWithFormat:@"%@/%@", myPath, [listOfFiles objectAtIndex: i]];

    // add every item with its attributes
    listOfFolders = [filemgr attributesOfItemAtPath:filePath error:NULL];

    // to avoid typo get the attribute and create a string
    controllDir = [filemgr attributesOfItemAtPath:@"/" error:NULL];
    NSString *toCheck = [NSString stringWithFormat:@"%@", [controllDir objectForKey:NSFileType]];   

    // the folder elements one by one
    NSString *fileType = [NSString stringWithFormat:@"%@", [listOfFolders objectForKey:NSFileType]];    


    if([toCheck isEqualToString:fileType])
        {
            NSLog(@"NAME: %@  TYPE: %@" ,[listOfFiles objectAtIndex:i],[listOfFolders objectForKey:NSFileType]);
        }                
}            

[pool drain];
return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

层林尽染 2024-10-23 06:57:14
    NSURL *url = [NSURL fileURLWithPath:@"/Users"];
    NSError *error;
    NSArray *items = [[NSFileManager defaultManager]
                      contentsOfDirectoryAtURL:url
                      includingPropertiesForKeys:[NSArray array]
                      options:0
                      error:&error];

    NSMutableArray *dirs = [NSMutableArray array];
    for (NSURL *url in items) {
        if (CFURLHasDirectoryPath((CFURLRef)url)) {
            [dirs addObject:url];
        }
    }
}

您可以通过这种方式来使用块:

NSPredicate *predicate = [NSPredicate predicateWithBlock:
        ^BOOL (id evaluatedObject, NSDictionary *bindings){
            return CFURLHasDirectoryPath((CFURLRef)evaluatedObject); }];
NSArray *dirs = [items filteredArrayUsingPredicate:predicate]);

值得注意的是,它只访问磁盘一次,并且不会花费任何时间来获取不需要的属性。一旦构建了 NSURL,您就可以随时判断它是否是一个目录,因为它以 / 结尾(这是指定的行为)。这就是 CFURLHasDirectoryPath() 所做的一切。它实际上并没有击中磁盘。

    NSURL *url = [NSURL fileURLWithPath:@"/Users"];
    NSError *error;
    NSArray *items = [[NSFileManager defaultManager]
                      contentsOfDirectoryAtURL:url
                      includingPropertiesForKeys:[NSArray array]
                      options:0
                      error:&error];

    NSMutableArray *dirs = [NSMutableArray array];
    for (NSURL *url in items) {
        if (CFURLHasDirectoryPath((CFURLRef)url)) {
            [dirs addObject:url];
        }
    }
}

You can get fancy with blocks this way:

NSPredicate *predicate = [NSPredicate predicateWithBlock:
        ^BOOL (id evaluatedObject, NSDictionary *bindings){
            return CFURLHasDirectoryPath((CFURLRef)evaluatedObject); }];
NSArray *dirs = [items filteredArrayUsingPredicate:predicate]);

Of note here is that it only hits the disk the one time, and it doesn't spend any time fetching unneeded attributes. Once you construct the NSURL, you can always tell if it's a directory because it ends in a / (this is specified behavior). That's all CFURLHasDirectoryPath() is doing. It doesn't actually hit the disk.

邮友 2024-10-23 06:57:14

简要想法(从手机发布):

  • 使用 NSDirectoryEnumerator
  • 它有一个名为 fileAttributes 将返回带有项目属性的 NSDictionary
  • NSDictionary 有一个 fileType 方法,该方法将返回一个常量来指示项目的类型。
  • 有一个名为 NSFileTypeDirectory 的很好的常量,您可以使用它进行比较。

Brief thoughts (posting from a cell phone):

  • use an NSDirectoryEnumerator.
  • it has a method called fileAttributes that will return an NSDictionary with the item's attributes.
  • NSDictionary has a fileType method that will return a constant to indicate the kind of the item.
  • there's a nice constant called NSFileTypeDirectory you can use for comparison.
北凤男飞 2024-10-23 06:57:14

这怎么样?

NSFileManager *fm = [NSFileManager defaultManager];
NSError *error;
NSArray *subpaths = [fm contentsOfDirectoryAtPath:myPath error:&error];
if (!subpaths) ...handle error.
NSMutableArray *subdirs = [NSMutableArray array];
for (NSString *name in subpaths)
{
    NSString *subpath = [myPath stringByAppendingPathComponent:name];
    BOOL isDir;
    if ([fm fileExistsAtPath:subpath isDirectory:&isDir] &&
        isDir)
    {
        [subdirs addObject:subpath];
    }
}

现在,subdirs 数组包含所有直接子目录。

How's this?

NSFileManager *fm = [NSFileManager defaultManager];
NSError *error;
NSArray *subpaths = [fm contentsOfDirectoryAtPath:myPath error:&error];
if (!subpaths) ...handle error.
NSMutableArray *subdirs = [NSMutableArray array];
for (NSString *name in subpaths)
{
    NSString *subpath = [myPath stringByAppendingPathComponent:name];
    BOOL isDir;
    if ([fm fileExistsAtPath:subpath isDirectory:&isDir] &&
        isDir)
    {
        [subdirs addObject:subpath];
    }
}

Now the subdirs array contains all of the immediate subdirectories.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文