Ignore .DS_Store and Icon files in a folder with Cocoa NSFIleManager

后端 未结 3 2069
忘了有多久
忘了有多久 2020-12-31 06:38

I\'m trying to remove specific files from a directory using NSFileManager. I would like to ignore the hidden .DS_Store and Icon files (the folder that I\'m checking has to h

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 06:55

    The filename of a folder's custom icon resource is "Icon\r" (Icon, followed by a carriage return).

    What I generally do when enumerating a directory in which I want to skip invisible items (those whose name starts with a "."), is to check for a prefix of @".":

    NSMutableArray *fullPaths = [NSMutableArray array];
    
    NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
    
    NSArray *subpaths = [fileManager subpathsAtPath:filePath];
    
    for (NSString *subpath in subpaths) {
       if ( ![[subpath lastPathComponent] hasPrefix:@"."] && 
            ![[subpath lastPathComponent] isEqualToString:@"Icon\r"]) {
            [fullPaths addObject:[filePath stringByAppendingPathComponent:subpath]];
       }
    }
    // continue
    

    The above code will work in 10.5 and later, (or even 10.0, I believe, if you changed the fast enumeration to use an NSEnumerator).

    P.S. If you are creating your NSFileManager using +defaultManager, then you shouldn't use the [manager release] line, as that would be over-releasing.

    So, instead of:

    NSFileManager *manager = [NSFileManager defaultManager];
    // 
    [manager release];
    

    do

    NSFileManager *manager = [[NSFileManager alloc] init];
    //
    [manager release];
    

    or

    NSFileManager *manager = [NSFileManager defaultManager];
    //
    

提交回复
热议问题