2016-06-27 96 views
0

我有一個代碼從NSCollectionView中刪除一個對象,但它只能刪除一個項目。在NSArray(「數組」)中,值是「2 4」,它返回2,4。但是當我運行代碼時,它只刪除「2」而不是「4」。索引從NSArray中刪除對象

日誌:

Click here for the image of the NSLOG.

守則

NSString* LibraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *plistPathSMSettings = [LibraryPath stringByAppendingString:stormarManagerSettingsPlistPath]; 
NSString *betasDef = [SMInAppCommunicationDEF stringByAppendingString:@"BETA App Id"]; 

NSString *indexOfApp = [Functions readDataFromPlist:plistPathSMSettings ForKey:betasDef]; 

if (!(indexOfApp == nil)) { 
    NSArray * array = [indexOfApp componentsSeparatedByString:@" "]; 
    NSLog(@"Array: ", array); 
    int currentValue = 0; 
    for (int i = 0; i < [array count]; i++) 
    { 
     currentValue = [(NSNumber *)[array objectAtIndex:i] intValue]; 
     NSLog(@"currentValue: %d", currentValue); // EXE_BAD_ACCESS 
      NSLog(@"x: %d", i); 
      [self.content removeObjectAtIndex:(currentValue)]; 
      [self.collectionView setContent:self.content]; 
      [self.collectionView reloadData]; 
      NSLog(@"next: %d", currentValue); // EXE_BAD_ACCESS 

    } 
} 
else if (indexOfApp == nil) { 
    [self.collectionView setContent:self.content]; 
    [self.collectionView reloadData]; 
} 
+0

'NSArray'是不變的,所以你不能刪除任何東西。 – Droppy

+0

我的意思是它需要從collectionview內容中刪除,這是NSMutableArray。但是這都寫。這是這個代碼的東西。 –

+0

您正在將NSString強制轉換爲NSNumber。非常非常不健康。 – gnasher729

回答

1

假設有一個包含[A,B,C,d]的索引一個可變數組是0,b 1,c 2,d 3。但是,如果您刪除索引1處的say元素,則數組包含[a,c,d],並且元素現在具有不同的索引a是0,c是1,d是2 ...

您的array是一個索引數組,因此您嘗試刪除索引2(第三個)處的元素,然後刪除索引4(第四個)處的刪除元素,但最初在索引5處(如4> 2 )...它真的是你想要的嗎? [e0,e1,e2,e3,e4,e5,e6 ...] - >在索引2處刪除 - > [e0,e1,e3,e4,e5,e6 ...]索引4 - > [e0,e1,e2,e3,e4,e6 ...]?

--add一個solution--

一個好的解決辦法是在降序的索引進行排序,並將它們除去的元素,即,如果索引是[5,2,7,1] - >排序[7 ,5,2,1] - >刪除第8,然後第6,然後第3和第2。通過這種方式可以確保刪除給定索引處的元素不會改變前面元素的索引。

+0

我通過切換數字來修復它。首先4然後2.所以它的「4 2」 –

+0

是的固定的方式,因爲我的答案如下,但它實際上並沒有解決問題,如果你想要刪除集合視圖中的許多元素 – Hazneliel

-1

這是正在發生的事情,可以說內容是這樣的:

0 1 2 3 4 
[A][B][C][D][E] 

而且你的陣列是2,4如你所說。然後在第一次迭代,2應刪除:

0 1 2 3 4 
[A][B][ ][D][E] 

內容現在是:

0 1 2 3 
[A][B][D][E] 

因爲一個元素已被刪除,內容的長度發生了變化,如果你現在嘗試刪除在4的元素,沒有什麼會發生,因爲在那個位置沒有元素。

嘗試開始前整理您的陣列從內容刪除它們:

NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)]; 

然後從sortedArray不從數組中刪除元素,

+0

沒有它不修復正確的,想想在你的情況下刪除4,然後2 ...'currentValue - 我'根本不代表任何東西(期望在「2 4」的特殊情況下)。一個好的解決方法是按降序排序索引並逐個刪除它們。 –

+0

你是對的,因此刪除我建議的修復 – Hazneliel

+0

它的工作壽,我試着用1,3,4 –