coredata 学习总结(八)

Integrating Core Data and Storyboards

core data 和xcode的storyboards特性融合的很好。允许你利用依赖注入模式。

 

Integrating Core Data with a Storyboard Segue

一个复杂的地方在于在table view数据对象和其子view controller间的传递。如果不用storyboard,一般复写其方法tableView:didSelectRowAtIndexPath:.但是,如果使用storyboard,这个方法不应该使用。应该通过prepareForSegue:sender:方法来处理。

以下的例子展示了一个view controlleryou一个table view来展示一系列的employees。当你选择了其中一个cell时,想显示一个employee的detail view。假设view controller已经有了一个属性来接收选择的NSManagedObject

objc

  1. @interface DetailViewController :UIViewController
  2.  
  3. @property (weak)AAAEmployeeMO *employee;
  4.  
  5. @end

swift

  1. class DetailViewController:UIViewController {
  2.  
  3. weak varemployee: AAAEmployeeMO?
  4.  
  5. }

注意

无论何时你在应用程序中传递NSManagedObject引用,最好将它们设定为weak引用属性。这个防止当NSManagedObject被删除时view controller为这个已经不存在的对象留下一个野引用。当这个属性被声明为weak时,如果对象被删除,他会自动被设置为nil。

接下来你实现方法prepareForSegue:sender:来传递合适的NSManagedObject实例

objc

  1. #define CellDetailIdentifier @"CellDetailIdentifier"
  2. - (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
  3. {
  4. id destination= [segue destinationViewController];
  5. if ([[segueidentifier] isEqualToString:CellDetailIdentifier]){
  6. NSIndexPath *indexPath= [[self tableView] indexPathForSelectedRow];
  7. id selectedObject= [[self fetchedResultsController] objectAtIndexPath:indexPath];
  8. [destinationsetEmployee:selectedObject];
  9. return;
  10. }
  11. }

swift

  1. let CellDetailIdentifier ="CellDetailIdentifier"
  2. override funcprepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  3. switch segue.identifier! {
  4. case CellDetailIdentifier:
  5. let destination =segue.destinationViewController as! DetailViewController
  6. let indexPath =tableView.indexPathForSelectedRow!
  7. let selectedObject =fetchedResultsController.objectAtIndexPath(indexPath)as! AAAEmployeeMO
  8. destination.employee =selectedObject
  9. default:
  10. print("Unknown segue:\(segue.identifier)")
  11. }
  12. }

Once the segue identifier (which is required to be unique per segue in a storyboard) is retrieved from the segue, you can safely assume what type of class the destination view controller is, and pass a reference to the selected Employee instance to the destination view controller. The destination view controller will then have the reference available to it during the loading portion of its life cycle and display the data associated with it. This is dependency injection in that the parent view controller is controlling the flow of the application by deciding which Employee instance to hand off to the destination view controller.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值