2012-09-10 76 views
4

我使用的Xcode進行iPhone應用程序和下面的目錄結構訪問所有圖像文件夾中的iPhone應用程序

GFGGAME 
    -gfggame.xcodeproj 
    -Images 
    --bagold 
    ---bags_1.png 
    ---bags_2.png 
    --bagsnew 
    ---bags_5.png 
    ---bags_6.png 

我想從文件夾bagsoldbagsnew訪問所有圖像。如果我爲png使用資源路徑和謂詞過濾器,它會給我所有的png文件。有沒有一種方法可以訪問文件夾中的文件。

回答

3

我想你可能想用這個NSBundle方法:

+ (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)bundlePath 

See API docs here

您會通過@".png"爲您的擴展,然後指定只爲你想要的子目錄的目錄路徑(您可能需要調用兩次,每個子目錄一次,然後將第二個路徑數組追加到第一個)。

See a similar question on Stack Overflow here

上述注意在回答(鏈接)的點,你需要什麼在Xcode做才能使這項工作。

+0

的NSString * bundlePath = [[[一個NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@ 「/圖像」]; NSArray * files = [NSBundle pathsForResourcesOfType:@「。png」inDirectory:bundlePath]; for(NSString * fn in files) NSLog(@「%@」,fn); 這是沒有圖像返回給我。如果我沒有將圖像追加到資源路徑中,我會獲得所有文件夾中的所有圖像 – ila

+0

@ila,我認爲您的路徑中有一個額外的斜槓('/')('@「/ Images」')。 ..儘管*可能*不會傷害。另外,您是否在我鏈接到的答案末尾註釋了評論(他在哪裏說「但...」)?是你做的嗎? – Nate

2

這樣做:

NSString *bundleRootpath = [[NSBundle mainBundle] bundlePath]; 
NSString *filePath = [bundleRootpath pathForResource:@"bags_1" ofType:@"png" inDirectory:@"Images/bagold"] 
NSFileManager *fileMangr = [NSFileManager defaultManager]; 
NSArray *dirContents = [fileMangr contentsOfDirectoryAtPath:bundleRootpath error:nil]; //your path here it may be document directory also 

過濾JPG如有

NSArray *onlyJPGs; 
if([dirContents count] > 0){ 
NSPredicate *fltrJPG = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]; 
onlyJPGs = [dirContents filteredArrayUsingPredicate:fltrJPG]; 
} 

現在PNG如有

NSArray *onlyPNGs; 
if([dirContents count] > 0){ 
NSPredicate *fltrPNG = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"]; 
onlyPNGs = [dirContents filteredArrayUsingPredicate:fltrPNG]; 

搜索任何其他格式,如果任何

合併onlyJPGs和只有PNG成一個數組

+0

我在獲取Images/bagsold文件夾的路徑時遇到問題。我怎麼弄到的? – ila

3

從您對其他已回答的人的回覆中,聽起來像您已將文件夾與Xcode組混淆在一起。 Xcode組不對應於設備上的文件夾。他們僅僅是爲了幫助你保持你的Xcode項目組織爲,而不是設備。任何資源都可以通過平面層級直接複製到主目錄包中。

當拖動文件夾到的Xcode將它添加到一個項目,你需要選擇「創建任何添加的文件夾文件夾引用」「創建任何添加的文件夾組」。這將在構建應用程序時保留目錄佈局。

+0

非常感謝我在這裏錯了 – ila

1

只是爲了各種:)

NSMutableArray *filePaths = [NSMutableArray arrayWithArray:[NSBundle pathsForResourcesOfType:nil inDirectory:fullPathToFolder]]; 
    NSMutableArray *toDelete = [NSMutableArray array]; 
    if(filePaths.count>0){ 
     [filePaths enumerateObjectsUsingBlock:^(NSString* obj, NSUInteger idx, BOOL *stop) { 
      if(!([obj hasSuffix:@"jpg"] || [obj hasSuffix:@"png"])){ 
        [toDelete addObject:obj]; 
      } 
     }]; 
    } 
    [filePaths removeObjectsInArray:toDelete]; 
    return filePaths; 
相關問題