如何从文档目录中提取路径组件直到我的文件名?

时间:2012-02-02 05:21:01

标签: iphone objective-c xcode cocoa-touch ios5

在我的iPhone应用程序中,

我想提取路径组件....

/Users/priyadarshanjoshi/Library/Application Support/iPhone Simulator/5.0/Applications/A2CD9285-62E9-4447-9945-5D8CE090FB3A/Documents/Wine_12.png

我想提取

/Documents/Wine_12.png

我正在写这段代码......

有更简单的方法吗?

NSString *relativePathImage1=@"";
        BOOL append=NO;
        for(NSString *get in [imagePath pathComponents])
        {
            if([get isEqualToString:@"Documents"])
            {
                append=YES;
            }
            if(append==YES)
            {
            relativePathImage1=[relativePathImage1 stringByAppendingPathComponent:get];
            }
    }
        NSLog(@"relativePathImage1 %@",relativePathImage1);

3 个答案:

答案 0 :(得分:3)

NSString *fullPath = // Get the path to your image
NSString *pathWithNoFileName = [fullPath stringByDeletingLastPathComponent];
NSString *myPath = [[pathWithNoFileName lastPathComponent] stringByAppendingPathComponent:[fullPath lastPathComponent]];

答案 1 :(得分:2)

为什么不借助以下功能?它将导致数组中的2个字符串,在文档之前和文档之后。然后,Yu可以在文档之后使用字符串并在其中附加文档/并使用它。

   [strPath componentsSeparatedByString:@"Document"]

答案 2 :(得分:1)

方法lastPathComponent将为您提供Wine_12.png

方法stringByDeletingLastPathComponent将为您提供/Users/priyadarshanjoshi/Library/Application Support/iPhone Simulator/5.0/Applications/A2CD9285-62E9-4447-9945-5D8CE090FB3A/Documents

你可以拿第二个lastPathComponent然后合并。