2014-01-13 76 views
0

在我的應用程序中,我設置了NSArray,並將所有具有HTML文件擴展名的對象從文檔目錄添加到它。
我使用這個數組來填充UITableView但是...我不斷得到警告NSArray VS. NSMutableArray問題

'NSArray' may not respond to 'removeObjectAtIndex:'

如果我將其更改爲NSMutableArray則該警告會消失,但新的警告這裏彈出:

self.files = [[[manager contentsOfDirectoryAtPath:documentsDirectoryPath 
              error:nil] 
          pathsMatchingExtensions:[NSArray arrayWithObjects:@"html", nil]] retain]; 

這一警告是:

Incompatible pointer types assigning to 'NSMutableArray *' from 'NSArray *'

的應用程序工作正常,如編輯表格視圖從來沒有產生任何親儘管存在removeObjectAtIndex:問題。

+0

長的語句分解爲單獨的線,它是一個更容易發現錯誤。你會立即看到'[[manager contentsOfDirectoryAtPath:documentsDirectoryPath error:nil]'返回了一個'​​NSArray'而不是一個NSMutableArray。 OPr在該線上找到指出錯誤的錯誤。在一條線上組合操作沒有收益。 – zaph

回答

1

使用mutableCopy而不是retain

self.files = [[[manager contentsOfDirectoryAtPath:documentsDirectoryPath error:nil] 
       pathsMatchingExtensions:[NSArray arrayWithObjects:@"html", nil]] 
       mutableCopy]; 
+1

@Zaph:這與ARC沒有任何關係(除非你需要在沒有ARC的情況下添加'autorelease'),而是把一個NSArray轉換成一個'NSMutableArray'。 – DarkDust

+0

@Zaph:那你爲什麼首先提到ARC? – DarkDust

1

pathsMatchingExtensions返回一個普通的NSArray對象。

當我需要一個可變數組但是得到一個不可變數組時,我經常會使用[NSMutableArray arrayWithArray:anArray]

在你的情況,你可能你的代碼行更改爲:

self.files = [NSMutableArray arrayWithArray:[[manager contentsOfDirectoryAtPath:documentsDirectoryPath error:nil] 
                 pathsMatchingExtensions:[NSArray arrayWithObjects:@"html", nil]]]; 
+0

''[anArray mutableCopy]'不那麼打字;-)除非你不使用ARC,但我仍然更喜歡'[[anArray mutableCopy] autorelease]'...我認爲其意圖更清楚,但它只是一個品味的問題。 – DarkDust

+0

@DarkDust你已經有了一個點:)我只是留下這個答案作爲另一種選擇。 – Aaron

+0

謝謝@Aaron。我標記了另一個答案是正確的,因爲它是第一個發佈的。它不會讓我馬上接受,所以這就是爲什麼在你發佈這個消息時沒有人接受。 – user717452