将NSMutableArray保存到Core Data [英] Saving an NSMutableArray to Core Data

查看:118
本文介绍了将NSMutableArray保存到Core Data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的核心数据模型中添加NSStrings的NSMutableArray到我的一个实体。问题是,这不是Core Data中支持的类型。

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.

我尝试创建一个可转换的属性,但问题是我没有办法将NSMutableArray转换为NSData,然后从NSData转回NSMutableArray。任何人都有一个想法,如何解决这个问题?

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?

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

(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.

***编辑:这里是如何将数组归档到NSData,以便它可以在您的托管对象中使用***

**** Here's how to archive the array into NSData so that it can be used in your managed object***

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

基本上,任何符合NSCoding协议的类都可以通过这种方式归档。 NSArray / NSMutableArray已经符合它了。他们告诉他们所有的对象归档自己,所以他们也必须遵守。

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.

由于你的数组是符合的,并且它是一个NSString数组(它也符合),那么这个对象的成员必须符合等等。你是金的。

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

这篇关于将NSMutableArray保存到Core Data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆