2012-11-05 183 views
2

代码:获取文件夹名称和图像名称

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 

的路径从上面的路径我需要找回只有“原/ 1-1.jpg” 。 请帮我.....

+0

参见[此](http://stackoverflow.com/questions/8079711/getting-the-last-2-目录的文件路径)和[本](http://stackoverflow.com/a/9107645/1126111) – Hector

回答

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 
+0

工作很好谢谢 –

1

你可以使用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]; 
2

有几种方法对皮肤一只猫:

NSString* lastFile = [path lastPathComponent]; 
NSString* lastDir = [[path stringByDeletingLastPathComponent] lastPathComponent]; 
NSString* fullLast = [lastDir stringByAppendingPathComponent:lastFile]; 
相关问题