2013-03-02 82 views
1

我想過濾的格式[數字] _ [數字] png格式 的文件路徑的數組並獲得唯一開始一個具體數字的,說1過濾文件路徑中使用NSPredicate

這是我試過的:

NSPredicate *predicate = [NSPredicate predicateWithFormat: 
          @"self MATCHES '%@/1_[0-9]+.png'", 
          [[[NSBundle mainBundle] resourcePath] 
           stringByAppendingPathComponent:@"Images"]]; 

NSArray *files = [[[NSBundle mainBundle] pathsForResourcesOfType:@"png" 
             inDirectory:@"Images"] 
        filteredArrayUsingPredicate:predicate]; 

我得到一個空的數組。 我嘗試使用LIKE而不是MATCHES。我嘗試使用[cd]標誌,儘管它應該沒關係。仍然我總是得到一個空陣列。 這是正則表達式嗎?


編輯:

這似乎是問題是與predicateWithFormat。

我認爲它得到一個格式字符串,後面跟着要替換爲格式字符串的參數。它不這樣工作。它忽略了參數,並且在格式字符串中沒有任何東西被替換。

因此,解決辦法如下:

NSPredicate *predicate = [NSPredicate predicateWithFormat: 
          [NSString stringWithFormat: 
          @"self MATCHES '%@/1_[0-9]+.png'", 
          [[[NSBundle mainBundle] resourcePath] 
           stringByAppendingPathComponent:@"Images"]]]; 

NSArray *files = [[[NSBundle mainBundle] pathsForResourcesOfType:@"png" 
             inDirectory:@"Images"] 
        filteredArrayUsingPredicate:predicate]; 

回答

0

它看起來像問題是代碼的第一和第二線之間的衝突。第一行設置您的NSPredicate所以它的格式是這樣的:

Images/1_#.png 

在你的第二行,你說的iOS尋找你的謂語Images目錄內。通過這樣做,你最後的謂詞/路徑是這樣的:

Images/Images/1_#.png 

刪除追加Images/目錄謂詞的開始NSPredicate的一部分。

上面描述的問題可能不是問題。代碼的另一個可能的問題是您的謂詞格式不正確。在您的原始代碼中,您忘記在NSPredicate中的1之後添加+(您在[0-9]之後執行了此操作,但未執行1)。

您的代碼應該是這個樣子:

NSString *filter = @"1+_[0-9]+.png"; 
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"self MATCHES %@", filter]; 
NSArray *files = [[[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:@"Images"] filteredArrayUsingPredicate:predicate]; 

當我在我的應用程序NSPredicate成功篩選一個NSString測試上面的代碼。

你也可能想看看這個鏈接:http://useyourloaf.com/blog/2010/07/27/filtering-arrays-with-nspredicate.html

+0

@ Ata01是,'MATCHES'是你正在尋找在這種情況下。我編輯了我的答案 - 請在最後查看編輯後的代碼。我還添加了另一個可能的解釋。 – 2013-03-02 13:25:12

+0

我已經嘗試了'1'後帶加號的謂詞,沒有它,它在兩種情況下都不起作用。我不認爲使用加號在我的情況下是正確的,因爲我只需要一個數字'1',而不是一個或多個。我嘗試使用你鏈接的代碼,它確實有效,但它只接受文件名並對它們進行過濾。所以我可以這樣做。剝離路徑,過濾文件名,然後添加完整路徑,但如果可能,我想對完整路徑進行過濾。 – Ata01 2013-03-02 18:06:02