本文介绍了从包含nsdictionary的nsmutablearray中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从nsmutablearray中删除重复项。
I want to remove duplicates from nsmutablearray.
数组结构: -
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 0;
"act_id" = 2;
}
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 1;
"act_id" = 2;
}
{
"act_end_date" = "";
"act_entry_date" = "16/11/2014";
"act_recurrrance_type" = Daily1;
"act_start_date" = "2014-11-15";
"row_id" = 2;
"act_id" = 3;
}
)
我想要的是检查数组包含任何字典whi的位置ch有相同的act_id。
如果是,则删除第一个字典。
即上述数组的预期结果: -
What I want is to check where array contain any dictionary which have same act_id.If yes then remove 1st dictionary.i.e the expected result for the above arrayis :-
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 1;
"act_id" = 2;
}
{
"act_end_date" = "";
"act_entry_date" = "16/11/2014";
"act_recurrrance_type" = Daily1;
"act_start_date" = "2014-11-15";
"row_id" = 2;
"act_id" = 3;
}
)
他们有什么办法吗?
可以使用NSPREDICATE吗?
Is their any way?Is it possible by using NSPREDICATE?
我试图用以下方式做到: -
I Tries to do it in below way :-
NSMutableArray *filteredArray = [NSMutableArray array];
for (NSMutableDictionary* E1 in Event_Array)
{
BOOL hasDuplicate = [[filteredArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"act_id == %@", [E1 objectForKey:@"act_id"]]] count] > 0;
if (!hasDuplicate)
{
[filteredArray addObject:E1];
}
}
因为它返回数组:---
For it returns array :---
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 0;
"act_id" = 2;
}
)
我想要的是
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 1;
"act_id" = 2;
}
)
推荐答案
假设你想要最新的对象将在列表中。
Assuming you want the latest object to be in the list.
解决方案1:(简单)
反转你的数组
NSMutableArray *filteredArray = [NSMutableArray array];
for (int i = Event_Array.count-1; i>= 0; i--)
{
NSMutableDictionary* E1 = [Event_Array objectAtIndex:i];
BOOL hasDuplicate = [[filteredArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"act_id == %@", [E1 objectForKey:@"act_id"]]] count] > 0;
if (!hasDuplicate)
{
[filteredArray addObject:E1];
}
}
解决方案2:
使用NSMutableDictionary而不是数组。
Use NSMutableDictionary instead of array.
//Keys are act_id(s)
"2" = {
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 1;
"act_id" = 2;
};
"3" = {
"act_end_date" = "";
"act_entry_date" = "16/11/2014";
"act_recurrrance_type" = Daily1;
"act_start_date" = "2014-11-15";
"row_id" = 2;
"act_id" = 3;
}
这篇关于从包含nsdictionary的nsmutablearray中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!