使用MagicalRecord插入后CoreData关系不会更新

时间:2014-09-08 15:03:13

标签: ios core-data swift magicalrecord

我有一个有两个视图的应用。第一个允许在Core Data中创建多个实体,第二个允许显示创建的实体的数据。

在我的CoreData数据模型中,我有两个实体:

CD_AProductCD_AProductItems

CD_AProduct包含名为productItems的可选关系,其中CD_AProductItems

enter image description here

CD_AProductItems包含名为product witch CD_AProduct

的非可选关系

enter image description here

AppDelegate类中,我像这样实例化核心数据栈:

MagicalRecord.setupAutoMigratingCoreDataStack()

第一个视图的代码

然后在我的代码中,我第一次创建四个CD_AProductItems并链接关系:

if let entity = CD_ProductItem.MR_createEntity() as? CD_ProductItem
{
    product.addProductItemsObject(entity)

    entity.product = product

    success()
}
else
{
    failure()
}

然后,我将实体保存在持久存储中:

NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreWithCompletion({(successBlock : Bool, error : NSError!) in

        if successBlock
        {
            success()
        }
        else
        {                            
            if error != nil
            {
                failure()
            }
            else
            {
                success()
            }
        }
    }
)

第二个视图的代码

// Product is retrieved with CD_AProduct.MR_findFirstByAttribute
for productItem in product.productItems
{
    println("productItem: \(productItem)")   
}

现在这有什么不对。

  • 第一个视图:用户“选择”要添加到产品中的4个产品项目。
  • 点击我视图的右上角按钮进入下一个视图。
  • 第二个视图:显示创建的4个产品项的数据。
  • 使用我视图的左上角按钮返回第一页。
  • 第一个视图:在我的产品中再添加4个产品
  • 转到下一页
  • 第二个视图:仅显示4个产品而不是8个!

我认为这个问题来自核心数据堆栈,当我转到第二个视图(显示所选产品的数据的那个视图)时,它没有更新。

有关发生了什么的建议以及如何确保在转到第二个视图之前已更新整个Core Data Stack?

1 个答案:

答案 0 :(得分:0)

据我所知,你需要在不同的indexPath中使用不同的元素,因此在这种情况下,你应该在转到下一个viewController之前找到indexPath。此时您正在加载包含product.productItems的所有项目。因为这里的帖子中的代码很少,可以想象你有UITableView作为第一个控制器。

首先,您将需要创建一个存储CD_AProduct元素的数组:

var productArrays = [CD_AProduct]!

您已保存功能,因此我们将在此处跳过此步骤。

然后只需创建简单的prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if (segue.identifier == "GoToDetailView") {
      let vc = segue.destinationViewController as! CD_AProductItemsView
      let CD_AProduct = productArrays[tableView.indexPathForSelectedRow()!.row]
      vc.CD_AProductDetailView = CD_AProduct
      vc.CD_AProductItemsDetailView = productArrays.detailEntities.allObjects as! Array
  }
}

最后一行中的P.S detailEntities表示托管对象列表中的NSSet。你应该改变它。

现在,如果您运行您的应用程序,它将崩溃,因为此时tableView.indexPath将为零,因为没有人将此信息提供给prepareForSegue。因此,要解决此问题,我们应该使用didSelectRowAtIndexPath

self.performSegueWithIdentifier("GoToDetailView", sender: self)

我们完成了!它的答案非常晚,但也许会帮助别人。

相关问题