2016-11-17 68 views
0

我有一個包含NSIndexPath的數組,我想刪除所有具有相同IndexPath.Row的對象。我目前的代碼有一些問題,並不是所有具有相同行的對象都被刪除。 我的代碼是:Objective-C從包含索引路徑的NSArray中刪除對象

rowValue=(int)btn.tag; 
for (int i=0; i<[SingletonClass singleton].arraySubMenuItems.count; i++) 
{ 
    NSIndexPath * Path = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; 
    int section = (int) Path.section; 
    if (section == rowValue) 
    { 

     NSIndexPath *indexPath = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; 
     [[SingletonClass singleton].arraySubMenuItems removeObjectAtIndex:i]; 

    } 
} 
+0

您正在迭代並同時修改您的數組(尤其是刪除項目)。 – Larme

+0

是的,我知道。我該怎麼辦? –

+0

你可以使用每一個,然後刪除該對象[[SingletonClass singleton] .arraySubMenuItems removeObject:indexPath]; –

回答

2

您可以刪除對象這樣

rowValue=(int)btn.tag; 
NSMutableArray *arrTemp = [NSMutableArray new]; 
for (int i=0; i<[SingletonClass singleton].arraySubMenuItems.count; i++) 
{ 
    NSIndexPath * Path = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; 
    int section = (int) Path.section; 
    if (section == rowValue) 
    { 
     [arrTemp addObject:[[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]]; 
    } 
} 
[[SingletonClass singleton].arraySubMenuItems removeObjectsInArray:arrTemp]; 
+0

你救了我:D –

+0

很高興幫助:) – Rajat

0
rowValue=(int)btn.tag; 

int countItem = [SingletonClass singleton].arraySubMenuItems.count; 

for (int i=0; i < countItem ; i++) 

{ 

NSIndexPath * Path = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; 

    int section = (int) Path.section; 

    if (section == rowValue) 
    { 

     NSIndexPath *indexPath = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; 
      [[SingletonClass singleton].arraySubMenuItems removeObjectAtIndex:i]; 

    } 
} 

店的數量在不同的變量和運行循環,因爲當你從indexpath它改變刪除您的項目的總數。

0

您可以採用要在索引集中刪除的項目的索引,並按索引刪除項目。 這就是我所做的。

rowValue=(int)btn.tag; 
     NSMutableIndexSet *indicesToRemove = [[NSMutableIndexSet alloc]init]; 
    for (int i=0; i<[SingletonClass singleton].arraySubMenuItems.count; i++) 
    { 
     NSIndexPath * Path = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; 
     int section = (int) Path.section; 
     if (section == rowValue) 
     { 
     [indicesToRemove addIndex:i] 
     } 
    } 
    [[SingletonClass singleton].arraySubMenuItems removeObjectsAtIndexes:indices];