【发布时间】:2016-01-22 17:21:09
【问题描述】:
我有 2 个实体:
- 待办事项
- 日期
它们之间存在反比关系,因此一个 Todo 对象可以有多个 Date,因此 Todo 具有属性:
@NSManaged var dates: NSSet?
@NSManaged var name: String?
每个 Dates 对象可以有一个 Todo,所以它有属性:
@NSManaged var todo: Todo?
@NSManaged var wasDone: NSNumber? //It is a boolean
@NSManaged var date: NSDate?
当我创建一个 Todo 时,我会在实体名称中插入新对象。
//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
然后我计算日期,我想将它们插入到 Todo 的 NSSet 中(我在 Todo 中做了一个函数:
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)
这是第一个问题——我是否正确地创建了对象之间的关系?
然后我想从 Todo 的 NSSet 创建(在 cellForRowAtIndexPath 中,因为它显示在 tableView 中)一个数组:
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 时,它告诉我“在解开可选值时意外发现 nil”,但我知道其中存在带有“Date”类型对象的 fetchedData。
我做错了什么或没有做什么?
【问题讨论】: