【发布时间】:2015-08-05 03:32:03
【问题描述】:
我是 Swift 2.0 的新手,也是 Core Data 的新手。
我正在寻找“取消扁平化”各种核心数据NSManagedObjects。现在,我正在使用谓词并加入属性“parentNameID”和“nameID”。我确实在 Core Data GUI 中设置了 itemCategory 和 itemCategoryChildren 关系,我想继续加入这种关系,而不是通过 parentNameID>nameID 和谓词进行“平面”连接。我怀疑我真的很近,但我的 fetchedResultsParentID 容器总是空的。
请不要引导我使用 SuperAwesomeAPI 或 StudlyGreatAPI;我希望通过本机核心数据调用来做到这一点。我看到本来可以很有价值的讨论被随便提及使用的外部 API 所扼杀。
我正在尝试将我的一个类与工厂方法--enumerate()--转换为核心数据。 enumerate() 调用按预期工作——返回一个类对象数组——当我的类属于 NSObject 时——但我似乎无法将 NSManagedObjects 的分类“展开”成一个完整的核心数据关系。
我有什么:一个项目类(NSObject)和一个工厂类函数enumerate(),它返回一个项目数组。
我想要什么: 一个 Items 类 (NSManagedObject) 和一个返回 NSManagedObjects 的工厂类函数 enumerate()。
我做了什么:在enumerate() 中设置了项目属性,并生成了这些项目的数组。我在外部调用enumerate(),来自AppDelegate.Swift 文件:var items = Item.enumerate(),然后通过setValue() 在NSManagedObject 上设置属性。
我查看了各种各样的答案,我真正能找到的关于工厂和核心数据的唯一内容是this post。
我当然不会从 JSON 或 XML 文件中获取这些项目,并且将来可能会采用这种方式,但这似乎比创建数组的工厂类更难。如果没有,请告诉我!!
相关AppDelegate.Swift函数:
func preloadData(EntityName: String) {
// Remove any data that may exist
removeData(EntityName)
var items = AllItems.enumerate()
print("Array enumerated with \(items.count) items.")
for item in items {
let newItem = NSEntityDescription.insertNewObjectForEntityForName(EntityName, inManagedObjectContext: managedObjectContext) as NSManagedObject
// Required
newItem.setValue(item.isCategory, forKey: "isCategory")
newItem.setValue(item.name, forKey: "name")
newItem.setValue(item.shortDetail, forKey: "shortDetail")
newItem.setValue(item.itemID, forKey: "itemID")
if (item.parentItemID != nil) {
let fetchRequestParentID = NSFetchRequest(entityName:EntityName)
let predicateParentID = NSPredicate(format: "parentItemID == %i", item.parentItemID!)
fetchRequestParentID.predicate = predicateParentID
do {
let fetchedResultsParentID = try managedObjectContext.executeFetchRequest(fetchRequestParentID) as? [NSManagedObject]
// success ...
// THIS IS WHERE THINGS FAIL.
// newItem.setValue(fetchedResultsParentID, forKey: "itemCategory")
newItem.setValue(fetchedResultsParentID, forKeyPath: "itemCategory")
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
// let fetchRequestParentID = NSFetchRequest(entityName: EntityName)
// fetchRequestParentID.fetchLimit = 1
//
// let fetchedEntitiesParentID = self.managedObjectContext.executeFetchRequest(fetchRequestParentID)
//
// newItem.setValue(newItem, forKey: "itemCategory")
}
}
items.removeAll()
do {
try managedObjectContext.save()
} catch let error as NSError {
print("Failed: \(error.localizedDescription)")
}
}
【问题讨论】: