如何在Core Data中保留有序列表 [英] How can I preserve an ordered list in Core Data

查看:130
本文介绍了如何在Core Data中保留有序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个API方法,它从Web服务返回一个对象列表。此服务还会高速缓存结果,并尝试在再次访问Web服务之前返回高速缓存的结果(如果有)。所以我把这个列表存储在一个Core Data实体中。但Core Data只允许将to-may关系存储在NSSet中,这不会保持顺序。但我想要缓存的结果保留原始顺序(它最初是从Web服务)。我不一定知道该订单是如何建立的(所以我不能排序)。



那么如何保存这个订单呢?我的计划是存储一个字符串与对象ids,我可以稍后使用它来排序他们:

  NSString * objectIds = @ 1 5 2 9 4;这是最好的方法吗?


h2_lin>解决方案

如果您可以定位iOS 5,则可以使用新的 NSOrderedSet 特性,用于任意排序的核心数据关系。请参阅 iOS 5的核心数据发行说明有关此新功能的更多信息。



如果您必须支持iOS 4,那么您需要自己处理订单。一个常见的方法是添加一个整数属性到你的模型,然后你需要管理自己。然后,您可以在提取数据时对此属性进行排序。



将顺序存储在完全不同的字符串中似乎是错误的方式。如果排序很重要,这个信息应该在模型中,用户应该能够直接查询它(给我这个特定列表的前五个对象,或者什么是对象foo的索引)。不得不得到一个对象ID的字符串,解析它,然后查询某些对象ID对我来说感觉非常错误。


I'm writing an API method that returns a list of objects from a web service. This service also caches results and attempts to return the cached results (if any) before hitting the web service again. So I'm storing this list in a Core Data entity. But Core Data only allows to-may relationships to be stored in an NSSet, which does not preserve order. But I want the cached results to retain the original order (which was originally from the web service). I don't necessarily know how that order is established (so I can't sort).

So how can I preserve this order? My plan is to store a string with the object ids which I can later use to order them:

NSString *objectIds = @"1 5 2 9 4";

Is this the best way to do it?

解决方案

If you can target iOS 5 then you can use the new NSOrderedSet feature for arbitrarily-ordered Core Data relationships. See the Core Data Release Notes for iOS 5 for more information about this new feature.

If you have to support iOS 4 then you will need to handle the ordering yourself. A common way to do this is to add an integer property to your model which you then need to manage yourself. You can then sort on this property when fetching your data.

Storing the order in a completely different string seems like the wrong way to do it. If the ordering is important this information should be in the model and the user should be able to query for it directly ("give me the first five objects of this particular list", or "what is the index of object foo"). Having to get a string of object IDs, parse it, and then query for certain object IDs feels very wrong to me.

这篇关于如何在Core Data中保留有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆