将NSMutableArray保存到核心数据

时间:2023-01-30 16:31:49

I want to add an NSMutableArray of NSStrings to one of my Entities in my core data model. The problem is that this isn't a supported type in Core Data.

我想在我的核心数据模型中将NSStrings的NSMutableArray添加到我的一个实体中。问题是这不是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. Does anyone have an idea as to how this issue can be solved?

我尝试制作一个转换属性,但问题是我看不到将NSMutableArray转换为NSData,然后从NSData返回NSMutableArray。有没有人知道如何解决这个问题?

(I know I can archive the array, but I don't want to do that, I want it to be present in my model).

(我知道我可以存档数组,但我不想这样做,我希望它存在于我的模型中)。

1 个解决方案

#1


32  

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. NSArray/NSMutableArray already conform to it. 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.

基本上,任何符合NSCoding协议的类都可以这种方式存档。 NSArray / NSMutableArray已经符合它。他们告诉他们所有的对象都要自己存档,所以他们也必须遵守。并且所有这些对象的成员必须符合,等等。它就像一棵树。

Since your array conforms, and it's an array of NSString (which also conforms), then you're golden.

既然你的数组符合,并且它是一个NSString数组(也符合),那么你就是金色的。

#1


32  

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. NSArray/NSMutableArray already conform to it. 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.

基本上,任何符合NSCoding协议的类都可以这种方式存档。 NSArray / NSMutableArray已经符合它。他们告诉他们所有的对象都要自己存档,所以他们也必须遵守。并且所有这些对象的成员必须符合,等等。它就像一棵树。

Since your array conforms, and it's an array of NSString (which also conforms), then you're golden.

既然你的数组符合,并且它是一个NSString数组(也符合),那么你就是金色的。