简体   繁体   English

将NSMutableArray保存到核心数据

[英]Saving an NSMutableArray to Core Data

I want to add an NSMutableArray of NSStrings to one of my Entities in my core data model. 我想将NSStrings的NSMutableArray添加到我的核心数据模型中的一个实体中。 The problem is that this isn't a supported type in Core Data. 问题是这不是Core Data中支持的类型。

I tried making a tranformable attribute, but the problem is that I see no way of turning a NSMutableArray to NSData, and then going from NSData, back to an NSMutableArray. 我尝试制作一个可转换的属性,但问题是我看不到将NSMutableArray转换为NSData,然后从NSData转回NSMutableArray。 Does anyone have an idea as to how this issue can be solved? 有没有人知道如何解决这个问题?

(I know I can archive the array, but I don't want to do that, I want it to be present in my model). (我知道我可以存档数组,但我不想这样做,我希望它存在于我的模型中)。

You could have a binary data attribute in your modeled object, archive the array to data, and hand it off to the object. 您可以在建模对象中具有二进制数据属性,将数组存档为数据,然后将其移交给对象。

But I think the better way would be to have a to-many relationship, instead of using an array directly. 但我认为更好的方法是建立一个多对多关系,而不是直接使用数组。

****Edit: Here's how to archive the array into NSData so that it can be used in your managed object*** ****编辑:以下是如何将数组存档到NSData中以便可以在托管对象中使用***

NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:[NSArray arrayWithObjects:@"1",@"2", nil]];

Basically, any class you have which conforms to the NSCoding protocol can be archived in this way. 基本上,任何符合NSCoding协议的类都可以这种方式存档。 NSArray/NSMutableArray already conform to it. NSArray / NSMutableArray已经符合它。 They tell all of their objects to archive themselves, so they must conform too. 他们告诉他们所有的对象都要自己存档,所以他们也必须遵守。 And all of those objects' members must conform, etc. It's like a tree. 所有这些对象的成员必须符合等等。它就像一棵树。

Since your array conforms, and it's an array of NSString (which also conforms), then you're golden. 既然你的数组符合,并且它是一个NSString数组(也符合),那么你就是金色的。

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

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