2012-11-05 45 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]; 
相關問題