我正在构建一个日志应用程序,在其中创建一个FocusArea对象,然后包含30个日志条目对象。
所以我在我的数据模型中创建了一对多关系。
然后我实现了两个NSManagedObject类:
@目标区域(FocusArea)
类焦点区域:NSManagedObject{
@NSManaged var focusName: String
@NSManaged var focusStart: NSDate
@NSManaged var focusEnd: NSDate
@NSManaged var completeFlag: Bool
//@NSManaged var entries: NSSet
var entries: NSMutableOrderedSet {
return self.mutableOrderedSetValueForKey("entries")
}
}
@objc(条目)
类条目:NSManagedObject{
@NSManaged var entryJournal: String
@NSManaged var entryDate: NSDate
@NSManaged var completeFlag: Bool
@NSManaged var entryStatus: Bool
@NSManaged var focus: FocusArea
}
我可以毫无问题地添加FocusArea,但是当我尝试创建30个Entry对象并存储在FocusArea.entries中时,所有的东西都会崩溃。
向FocusArea对象添加多个条目对象的正确方法是什么?
我离这儿远吗?
@IBAction func saveFocusArea(sender: AnyObject) {
if txtFocusName.text != nil {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!
//create new focus area
let entFocus = NSEntityDescription.entityForName("FocusArea", inManagedObjectContext: context)
let newFocus = FocusArea(entity:entFocus!, insertIntoManagedObjectContext: context)
newFocus.focusName = txtFocusName.text!
newFocus.focusStart = NSDate()
newFocus.focusEnd = NSDate().dateByAddingTimeInterval(60*60*24*30)
newFocus.completeFlag = false
//initialize 30 new entries into core data
let entEntry = NSEntityDescription.entityForName("Entry", inManagedObjectContext: context)
for var i = 0; i < 30; i++ {
let newEntry = Entry(entity:entEntry!, insertIntoManagedObjectContext: context)
let c = Double(i)
newEntry.entryDate = NSDate().dateByAddingTimeInterval(60*60*24*c)
newEntry.entryJournal = ""
newEntry.entryStatus = false
newEntry.completeFlag = false
//THIS IS THE PROBLEM AREA
newFocus.entries.append(newEntry)
}
do {
try context.save()
} catch {
print("There's a problem!")
}
}
}
最佳答案
我想出来了。我要做的就是:
newEntry.focus=新焦点。
因此,与其设置父对象与子对象之间的关系,不如将其从子对象设置为父对象。