【问题标题】:NSMutableArray Sorting and grouping with memory OptimisationNSMutableArray 使用内存优化排序和分组
【发布时间】:2012-12-15 20:25:59
【问题描述】:

NSArray 中有ItemObject。这个 ItemObject 不是根据 ItemID 分组的

json的Sample如下所示: 您会注意到 itemID“a123”、“a124”。可以有 n 个 itemID。

[
    {
        "ItemName": "John",
        "ItemID": "a123"
    },
    {
        "ItemName": "Mary",
        "ItemID": "a124"
    },
    {
        "ItemName": "Larry",
        "ItemID": "a123"
    },
    {
        "ItemName": "Michel",
        "ItemID": "a123"
    },
    {
        "ItemName": "Jay",
        "ItemID": "a124"
    }
]

上面的响应存储在NSArray中如下:

NSMutableArray *itemArray=[[NSMutableArray alloc] init];

ItemObject *obj=[[ItemObject alloc] init];
obj.itemName=@"John";
obj.itemID=@"a123";
[itemArray addObject:obj]

.....

ItemObject *objN=[[ItemObject alloc] init];
objN.itemName=@"Jay";
objN.itemID=@"a124";
[itemArray addObject:objN].

这表明,如果JSON中有N个项目,那么它将创建一个包含N个项目的数组。

上面的item在UItableView中显示正确。

现在,如果想要对它们进行排序并将它们放在 NSMutableArray 组中,那么最好的编码方式是什么,消耗的内存占用更少。 [即排序+分组] 我正在努力实现以下目标:

NSMutableArray *itemArray=[[NSMutableArray alloc] init];
at index 0: NSArray with itemID "a123"
at index 1: NSArray with itemID "a124"

由于可用的 ItemId 是动态的,正如我解释的那样,可能有“N”个 itemId。

第 1 步: 所以,我首先需要找到可用的 itemId。

第 2 步:

NSMutableArray *myArray=[[NSMutableArray alloc] init];
for(NSString *itemID in itemIDS){
 NSArray *itemsForID=[itemArray filterUsingPredicate:[NSPredicate predicateWithFormat:"itemID MATCHES %@",itemID]];
[myArray addObject:itemsForID];
}

myArray 是预期的结果。 但是使用 filterUsingPredicate "N" 次会很费时间和内存。

任何,帮助表示赞赏。

【问题讨论】:

  • 您是否可以控制来自 JSON 的 itemID,或者您是否需要添加新对象并为其分配下一个可用 ID?至于分组,您是否希望最终结构是一个数组数组,其中每个内部数组的对象都具有相同的 itemID?
  • 根据您将如何使用生成的对象,您可能会考虑使用一个字典,其中键是 itemID,值是 itemID 与该键匹配的所有 ItemObjects 的数组。
  • @rdelmar 我对 itemID 没有任何控制权。它们在响应中收到。最终结构是各自 ID 的数组中的数组。
  • 好吧,这种结构效率很低。如果您想提高效率,那么以 itemID 为键的字典会是更好的选择。

标签: objective-c ios memory nsmutablearray nsarray


【解决方案1】:

你能试试下面的代码吗?

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"itemID"  ascending:YES];
[itemArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

【讨论】:

  • 不错的答案,但它应该将结果分配给 myArray。
  • 在我的代码中有这个代码 sn-p 会很好。但是,我正在寻找内存和时间优化。
【解决方案2】:

您可以将数据保存为 NSManagedObjects。然后你可以使用NSFetchedResultsController 作为你的表的数据源(你设置了一个排序描述符和一个节名键路径):

NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
        initWithFetchRequest:fetchRequest
        managedObjectContext:context
        sectionNameKeyPath:nil
        cacheName:nil];

您还可以设置批量大小(一次从数据库中获取的最大对象数)。

希望这会有所帮助!

【讨论】:

    最近更新 更多