使用Cocoa-Touch从文件路径创建树结构对象

时间:2012-07-20 09:10:37

标签: objective-c ios cocoa-touch

我有一份文件清单及其路径。

Unsigned/Corporate Tax Return/Testing.docx
Signed/Report/fieldsInfo.pdf
Unsigned/Corporate Tax Return/testSecure.pdf
Unsigned/Corporate Tax Return/2012/fileCatcher.pdf
Unsigned/Corporate Tax Return/2012/taxReturn.pdf

从这里我想要一个树形结构的对象数组,其中放置所有这些对象。 我有两个对象类型:文档和文件

我如何在目标C中做到这一点?

到目前为止:

- (void) createFolderStructure:(Document *) doc{
    Folder * root = [[Folder alloc]init];

    NSArray * folders = [doc.documentFilePath componentsSeparatedByString:@"/"];

    for(NSString * folderName in folders){
        if([root.folderSubFolders count] == 0){
            //root is empty , create folder
            Folder * newFolder = [[Folder alloc]init];
            newFolder.folderName = folderName;
            [root.folderSubFolders addObject:newFolder];
        } else {
            //root has subfolders
            for(Folder * folder in root.folderSubFolders){
                if ([folder.folderName isEqualToString:folderName]) {
                    //folder exists in subfolders

                } else {
                    //folder doesn't exist ,create folder
                    Folder * newFolder = [[Folder alloc]init];
                    newFolder.folderName = folderName;
                    [root.folderSubFolders addObject:newFolder];

                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

NSString *str = @"Unsigned/Corporate Tax Return/2012/taxReturn.pdf";
NSArray *arr = [str componentsSeparatedByString:@"/"];

那么你有一个包含NSStrings的数组

0 - 未签名,1 - 企业纳税申报表......

执行此操作时:

id fileObj = [arr lastObject];

您将获得 File 对象,数组中的其余对象应为 Document 对象。