20

在我的应用程序中,我有一个NSDictionary其键应该是NSManagedObject.

然而,问题在于NSManagedObject它没有实现NSCopying协议,这意味着没有核心数据对象/实例NSManagedObject可以用作字典键,即使该-[hash]方法适用于它们。

我应该这样做吗?

4

4 回答 4

34
于 2009-09-30T13:49:38.770 回答
1

我建议使用 [[[myManagedObject objectID] URIRepresentation] absoluteString] 作为您的密钥。

于 2009-09-30T13:10:05.977 回答
0

您能否创建一个包装类,其中包含对您要用作字典键的 NSManagedObject 实例的引用?然后,您可以使这个包装类实现 NSCopying,以及一个散列方法(可能只是调用 NSManagedObject 的散列方法),并将这个包装类用作字典键。

于 2009-09-30T12:53:49.010 回答
0

I had a similar problem, in which I needed to bundle several entities with additional data for each, and initially tried:

@{entity1:data1, @entity2:data2, @entity3:data3}

this didn't work for the reason above (NSCopying), so I did:

@[
   @{@"entity":entity1, @"data":data1},
   @{@"entity":entity2, @"data":data2},
   @{@"entity":entity3, @"data":data3}
]

But this solution makes sense only if you don't need dictionary style access to these entities or are happy to iterate to find what you need. In my case this was a packaging problem. Note that if you pass these entities around the NSManagedObjectContext need to be the same to use them.

于 2013-01-10T06:59:10.413 回答