我得到了2個實體:對象斷層 - CoreData關係
- 藤
- 日期
它們與反比關係連接,一個ToDo對象可以有多個日期,所以待辦事項具有性能:
@NSManaged var dates: NSSet?
@NSManaged var name: String?
和每個日期對象可以有一個待辦事項,所以它有屬性:
@NSManaged var todo: Todo?
@NSManaged var wasDone: NSNumber? //It is a boolean
@NSManaged var date: NSDate?
當我創建一個待辦事項我在實體名稱中插入新的對象。
//Saving into local device context
guard let ourcontext = self.context else {print("no context");return}
guard let newTodo = NSEntityDescription.insertNewObjectForEntityForName("Todo", inManagedObjectContext: ourcontext) as? Todo else {return}
let myTodoName = self.addTodoView.searchTextField.text
newTodo.name = myTodoName
然後,我計算的日期,我想將它們插入到待辦事項的NSSet中(我做的待辦事項功能:
func addObject(value: Dates) {
let dates = self.mutableSetValueForKey("dates")
dates.addObject(value)
}
這樣計算的日期和他們,我的創造「datesArray」後要添加這些上面的NSSet所提到:
for _ in self.datesArray {
guard let newDate = NSEntityDescription.insertNewObjectForEntityForName("MedicineDates", inManagedObjectContext: ourContext) as? MedicineDates else {return}
newTodo.addObject(newDate)
這是第一個問題 - 做我創建正確對象之間的關係
?然後我想創建(在的cellForRowAtIndexPath,因爲這顯示在的tableView)從待辦事項的NSSet中的數組:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! TodoTableViewCell
guard let object = fetchedResultsController?.objectAtIndexPath(indexPath) as? Todo else {return cell}
的NSSet數組:
let fetchedData = object.dates?.allObjects as! [Dates]
let datesArray = [NSDate]()
for object in fetchedData {
datesArray.append(object.date!)
}
這裏是繁榮。當我嘗試解開object.date時,它告訴我「意外地發現了零,同時展開一個可選值」,但我知道具有「Date」類型的對象的fetchedData存在。
我做錯了什麼或者我沒有做過什麼?