【问题标题】:Get folder name and image name获取文件夹名称和图像名称
【发布时间】:2012-10-24 22:16:02
【问题描述】:

代码:

NSString *path = [[NSBundle mainBundle] pathForResource:[objDynaMoThumbnailImages objectAtIndex:eg] ofType:@"jpg" inDirectory:[objDynaMoProductImagePath objectAtIndex:eg]];

它会像这样检索路径

/Users/software/Library/Application Support/iPhone Simulator/6.0/Applications/61AE2605-CE8E-404D-9914-CDA9EBA8027C/DynaMO.app/original/1-1.jpg

从上面的路径我只需要检索“original/1-1.jpg”。 请帮帮我.....

【问题讨论】:

标签: ios objective-c cocoa


【解决方案1】:

如果资源位于应用程序包的任意子目录中,则可以使用以下代码。它没有假设资源恰好是捆绑路径下的一个子目录。

NSString *path = [[NSBundle mainBundle] pathForResource:...];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *relativePath;
if ([path hasPrefix:bundlePath]) {
    relativePath = [path substringFromIndex:([bundlePath length] + 1)];
} else {
    relativePath = path;
}

例如

path = /Users/software/Library/Application Support/.../DynaMO.app/sub/dir/image.jpg

会导致

relativePath = sub/dir/image.jpg

【讨论】:

    【解决方案2】:

    给猫剥皮有几种方法:

    NSString* lastFile = [path lastPathComponent];
    NSString* lastDir = [[path stringByDeletingLastPathComponent] lastPathComponent];
    NSString* fullLast = [lastDir stringByAppendingPathComponent:lastFile];
    

    【讨论】:

      【解决方案3】:

      你可以使用NSString的成员函数lastPathComponent。

      NSString filename = [yourString lastPathComponent];
      

      编辑:抱歉,您似乎不是从路径中查找文件名,而是从文件名的父文件夹开始的子路径。上面的方法只给你文件名字符串。但是你可以这样做..

      -(NSString *) getSubPath:(NSString*)origPath{
         NSArray * array = [origPath componentsSeparatedByString:@"/"];
         if(!array  || [array length] == 0 || [array length] == 1)
           return origPath;
         int length  =  [array length];
         return [NSString stringWithFormat:@"%@/%@", [array objectAtIndex:(length - 2)], [array lastObject]];
      }
      

      你可以这样使用它

      NSString *subPath  = [self getSubPath:origPath];
      

      【讨论】: