2012-10-13 46 views
1

我試過搜索谷歌,並提出幾乎沒有任何關於通過xcode在Mac上搜索文件和文件夾。搜索文件和文件夾驅動器

這是可能的和如何?任何代碼示例等

我曾經在delphi中編程,搜索路徑的代碼片段就是這樣。

procedure SearchFolders(path:string); 
var 
    sr : tsearchrec; 
    res: integer; 
    i:integer; 
begin 
    path:= includetrailingpathdelimiter(path); 
    res:= findfirst(path+'*.*',faAnyfile,sr); 
    while res = 0 do begin 
    application.processmessages; 
    if (sr.name <> '.') and (sr.name <> '..') then 
     if DirectoryExists(path + sr.name) then 
     SearchFolders(path + sr.name) 
     else 
      FileProcess.Add(path + sr.name); 
      FileSize:=FileSize+sr.Size; 
    res := findnext(sr); 
    end; 
    findclose(sr); 
end; 

要激活,其SearchFolders('C:\');並搜索路徑並將其存儲到字符串列表中。

它是如何在osx內完成xcode的?

回答

1

不幸的是,我並不完全理解你的代碼。但是,您通常會使用NSFileManager來詢問文件系統。

例如,爲了在特定的路徑列表中的所有文件(即文件和文件夾),你可以做到以下幾點:

- (NSArray *) listFilesAtPath:(NSString*)path { 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    BOOL isDir; 
    if(([fileManager fileExistsAtPath:path isDirectory:&isDir] == NO) && isDir) { 
     // There isn't a folder specified at the path. 
     return nil; 
    } 

    NSError *error = nil; 
    NSURL *url = [NSURL fileURLWithPath:path]; 
    NSArray *folderItems = [fileManager contentsOfDirectoryAtURL:url 
          includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey, nil] 
               options:NSDirectoryEnumerationSkipsHiddenFiles 
                error:&error]; 

    if (error) { 
     // Handle error here 
    } 
    return folderItems; 
} 

這裏是你如何使用這個方法的例子:

NSArray *folderItems = [self listFilesAtPath:@"/Users/1Rabbit/Desktop"]; 
for (NSURL *item in folderItems) { 
    NSNumber *isHidden = nil; 

    [item getResourceValue:&isHidden forKey:NSURLIsDirectoryKey error:nil]; 
    if ([isHidden boolValue]) { 
     NSLog(@"%@ dir", item.path); 
    } 
    else { 
     NSLog(@"%@", item.path); 
    } 
}