按插入顺序检索核心数据实体
我可以在 NSSortDescriptor 中使用内部 ID 变量或时间戳来按照插入顺序检索核心数据实体吗?
如果有更干净的方法,我宁愿不必创建此类属性,但如果没有其他选择,我显然会这样做。
Is there an internal ID variable or timestamp I can use in a NSSortDescriptor to retrieve Core Data entities in the order they were inserted?
I would rather not have to create such properties if there is a cleaner way, though will obviously do so if there are no other alternatives.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,如果您想要数据的排序顺序,您需要自己将其添加到您的实体中。但是,您可以轻松添加默认值为“NOW”的 NSDate 属性,以便它自动填充。
No, if you want a sort order for your data, you need to add that to your entities yourself. However you can easily add a NSDate attribute that has a default value of "NOW" so that it will auto-populate.
您还可以向实体添加一个属性,将其命名为“sortNum”之类的名称,并且每当您获取实体时,都会使用排序描述符来获取它。
第1步
添加排序属性,在本例中我将其命名为“displayOrder”
< img src="https://i.sstatic.net/v5kJ6.png" alt="核心数据:添加排序顺序">
第 2 步
将新项目附加或插入到您的列表。
第 3 步
对该实体中的所有内容进行排序并更新其排序值。
然后保存!
第 4 步
现在,下次执行提取请求时,请确保添加排序。
就是这样!
这应该可以很好地处理你的排序。老实说,有时这段代码确实会插入从顶部第二个而不是顶部的新项目,但 95% 的情况下,这段代码效果很好。不管怎样,你明白了这个想法,并且可以调整和改进它。
祝你好运。
You can also add an attribute to your entity, name it something like "sortNum", and whenever you fetch your entity you fetch it with a sort descriptor.
Step 1
Add the sort attribute, in this case I named it "displayOrder"
Step 2
Append or insert the new item to your list.
Step 3
Resort everything in that entity and update their sort value.
Then save!
Step 4
Now, next time you do a fetch request, make sure you add in the sort.
That's it!
That should handle your sort fairly well. To be honest, sometimes this code does insert my new items second from the top instead of the top, but 95% of the time this code works great. Regardless, you get the idea and can tweak and improve it.
Good luck.
在“NSFetchedResultsController”内部有一个 sortDescriptor
让 sortDescriptor = NSSortDescriptor(key: "dateSort", ascending: false)
创建一个“实体”。添加到上下文时,我填写了日期。 “日期()”
Inside the "NSFetchedResultsController" there is a sortDescriptor
let sortDescriptor = NSSortDescriptor(key: "dateSort", ascending: false)
Create an "entity". When adding to the context, I fill in the date. "Date()"