【问题标题】:Merge NSMutableArray element in the same array by string通过字符串合并同一数组中的 NSMutableArray 元素
【发布时间】:2018-03-25 00:36:12
【问题描述】:

我想要一个 NSMutableArray 中的组元素,就像这个问题: How to implement "group by values" in NSMutableArray?

但是,我的问题是在 NSMutableArray 内部我没有值,但是我有一个类模型的对象,例如:

@interface up : NSObject 

@property (nonatomic,strong) NSString *id;
@property (nonatomic,strong) NSString *name;

@end

有什么想法吗?

例子:

嗯,实际上我有一个 NSMutableArray 并且在这个数组的每个单元格中我都有一个类模型的对象。我要做的是创建一个新的数据结构,在其中根据 ID 合并对象。例如:

{
 id = 1;
 name = "test"; 

}
{
 id = 1;
 name = "test1"; 
}
{
 id = 2;
 name = "test2";
}
{
 id = 2; 
 name = "test3"; 
}
{
 id = 3;
 name = "test4"; 
}

结果:

    {
 id = 1;
 name = "test"; 
 name = "test1"; 
}
{
 id = 2;
 name = "test2";
 name = "test3"; 

}
{
 id = 3;
 name = "test4"; 
}

【问题讨论】:

  • 你想要的是this吗?
  • 不可能生成您的预期结果;你最终希望得到什么样的输出?

标签: ios objective-c data-structures nsmutablearray


【解决方案1】:
    NSMutableDictionary<NSString *, NSMutableArray<NSString *> *> *newDict =  NSMutableDictionary.new;
    for( UP *up in data) {
        if (!newDict[up.id]) {
            newDict[up.id] = NSMutableArray.new;
        }
        [newDict[up.id] addObject:up.name];
    }

newDict 是新的数据结构。

【讨论】:

  • 天哪。完美工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多