Objective-C从包含索引路径的NSArray中删除对象
问题描述:
我有一个包含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];
}
}
答
您可以删除对象这样
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
答
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它改变删除您的项目的总数。
答
您可以采用要在索引集中删除的项目的索引,并按索引删除项目。 这就是我所做的。
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];
您正在迭代并同时修改您的数组(尤其是删除项目)。 – Larme
是的,我知道。我该怎么办? –
你可以使用每一个,然后删除该对象[[SingletonClass singleton] .arraySubMenuItems removeObject:indexPath]; –