简体   繁体   English

使用NSMutableArray保存到核心数据

[英]Saving to Core Data with NSMutableArray

Been having a bit of a headache with this one and was wondering if someone could offer some advice! 对此感到有点头疼,想知道是否有人可以提供一些建议!

Im implementing persistent storage with Core Data. 我用核心数据实现持久存储。

I have two Entities Car and Driver. 我有两个实体汽车和驾驶员。 A car can have many drivers. 汽车可以有很多驾驶员。

  • In one view i am collecting the drivers and storing them to a NSMutableArray 在一个视图中,我正在收集驱动程序并将其存储到NSMutableArray

  • This array is getting passed to another view and at some point i will be saving it against a Car 这个数组被传递到另一个视图,在某个时候我将其保存在汽车上

What i would like to do is save each driver from the array in a seperate row in the table of drivers (Just their name (NSString) which will be assigned to a Car. 我想做的是将阵列中的每个驱动程序保存在驱动程序表的单独行中(只是将其名称(NSString)分配给汽车)。

  • I can create an entry in the database for Car but am struggling with saving each driver in a seperate row in the driver table assigned to that car. 我可以在Car的数据库中创建一个条目,但是很难将每个驱动程序保存在分配给该汽车的驱动程序表的单独行中。

Any suggestions or pointers in the right direction would be greatly appreciated! 任何建议或正确方向的指针将不胜感激!

Cheers :) 干杯:)

It would be difficult to encapsulate a complete solution to your answer, as your question is fairly broad without seeing your code. 很难为您的答案封装一个完整的解决方案,因为您的问题相当广泛,而又没有看到您的代码。

Try to walk through Apple's excellent Books and Recipes sample applications, which cover the Core Data concepts you'll need to progress with your own project. 尝试遍历Apple优秀的Books and Recipes示例应用程序,其中涵盖了开发自己的项目所需的Core Data概念。

You mention that you have both Car and Driver entities, yet it sounds like you're trying to save your driver names directly as attributes of a car. 您提到您同时拥有Car和Driver实体,但是听起来您正在尝试将驾驶员姓名直接保存为car的属性。 Why are you just saving their NSString *name to the car? 为什么只将他们的NSString *name保存到汽车上?

Instead of doing that, you should simply update the relationships between your car and its drivers. 而不是这样做,您只需要更新汽车与其驾驶员之间的关系即可。 If you implement your entities as custom classes (and I highly recommend it - see this ADC guide ), then when you want to update who drives what car, you can simply say: [car addDriversObject:driver] or [car removeDriversObject:driver] . 如果您将实体实现为自定义类(我强烈建议您- 参见本ADC指南 ),那么当您想更新谁开什么车时,您可以简单地说: [car addDriversObject:driver][car removeDriversObject:driver]

Like Alex said, you may want to ensure you have a firm grasp on Core Data before heading out on your own too far. 就像Alex所说的那样,您可能想确保自己对Core Data有了一个牢固的掌握,然后再自行解决。

i'm not a pro in using core data, but you can try to get data from your array using NSKeyArchiver and save returned NSData object to your database. 我不是使用核心数据的专家,但是您可以尝试使用NSKeyArchiver从数组中获取数据并将返回的NSData对象保存到数据库中。 it works fine with sqllite databases. 它与sqllite数据库一起正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM