将属性类型更改为 Transformable 。
Transformable
如果您正在使用mogenerator(您应该很好),则为可转换生成的默认类型是 id 。
id
让mogenerator生成特定类型 NSDictionary ,您可以添加自定义键 attributeValueClassName 有价值的 NSDictionary 对于属性。参考这个 截图 。
NSDictionary
attributeValueClassName
我有一个解决方案 只是保存 dictionaryObj.description 在核心数据中的字符串 在获取字典字符串时,您可以转换为字典
dictionaryObj.description
-(NSMutableDictionary *)getMetaDataDictionary:(NSString *)string { NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSPropertyListFormat format; NSMutableDictionary * metaDataDictionary; @try { NSError * error; metaDataDictionary = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:&format error:&error]; if(!metaDataDictionary) { NSLog(@"ERROR: COULD NOT PARSE META-DATA : %@", error.description); } } @catch(NSException * exp) { NSLog(@"DICTIONARY :: %@", exp.description); } return metaDataDictionary; }
有几种方法可以解决这个问题:
一个。创建一个代表NSDictionary的实体,以便每个字典键由实体属性表示。
湾如果您不喜欢创建单独实体的上述方法,则仍可以将NSDictionary存储到NSData类型的单个Core Data字段中,前提是您首先将NSDictionary序列化为NSData。
//NSDictionary to NSData NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:dictionary forKey:@"Some Key Value"]; [archiver finishEncoding]; // data is now ready to use
然后,当您从Core Data读取NSData时,您还需要将NSData转换回NSDictionary。
// NSData to NSDictionary NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; NSDictionary *dictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain]; [unarchiver finishDecoding]; // dictionary is now ready to use
C。最后,您可以使用持久性框架,例如Sensible TableView,其中自动获取,显示和保存所有数据结构。我自己省了很多代码。
你应该使用“Transformable Attributes”:
*.xcdatamodeld
NSManagedObject
*.h
其他一切都自动运作
有关更多信息,请参阅 https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdNSAttributes.html