如何同步Core Data关系?
我正在创建一个应用程序,它从 Web 服务器 (MySQL) 提取数据,解析它并使用 Core Data 将其存储在 SQLite 数据库中。
MySQL 数据库有一个“words”表。每个单词都可以属于一个“类别”。因此,words 表有一个用于连接表的“category_id”字段。
我在思考如何在我的应用程序中本地复制此内容时遇到一些困难。我目前有与 MySQL 数据库结构匹配的实体,但没有关系。似乎在我的“单词”实体中,我不需要“category_id”字段(我应该设置一对一的“类别”关系)。
我对如何保持核心数据关系与网络服务器同步感到困惑?
I'm creating an app that pulls data from a web server (MySQL), parses it and stores it in a SQLite database using Core Data.
The MySQL database has a 'words' table. Each word can be in a 'category'. So the words table has a field for 'category_id' to join the tables.
I'm having some trouble getting my head around how to replicate this locally in my app. I currently have entities matching the structure of the MySQL database, but no relationships. It seems like in my 'words' entity I shouldn't need the 'category_id' field (I should instead have a one-to-one 'category' relation set-up).
I'm confused as to how to keep this Core Data relationship in sync with the web server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您有一个用于
Word
和Category
的Entity
,您将需要建立一种关系(命名可能有点模糊)。另外假设一个类别可以有很多单词,并且您是对的,您不需要category_id字段,因为所有关系都是通过核心数据维护的对象图进行管理的。您仍然需要在每个实体中使用像
server_id
(或类似的)这样的主键,否则您将无法更新/查找已保存的对象。这就是我处理从外部数据库同步数据的方式(我使用带有 JSON 的 RESTful 接口,但这并不重要)
... @"(serverId IN %@)", PrimaryKeys 这样的谓词
这是按主键排序的。
Word
和Category
执行此操作我很难测试,但这应该给你一个起点?
很高兴看到 Shiny 课程的参加者使用堆栈溢出 - 不仅仅是我
Assuming you have an
Entity
forWord
andCategory
you will need to make a relationship (naming may be a bit hazy). Also assuming aCategory
can have many words andYou are correct you would not need the category_id field as all relationships are managed through the object graph that Core Data maintains. You will still need a primary key like
server_id
(or similar) in each entity or you will have trouble updating/finding already saved objects.This is how I deal with syncing data from an external database (I use RESTful interfaces with JSON but that does not really matter)
... @"(serverId IN %@)", primaryKeys
which is sorted by the primary key.
Word
andCategory
It's hard for me to test but this should give you a starting point?
Good to see a fellow Shiny course attendee using stack overflow - it's not just me