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
@interface DetailViewController :UIViewController
@property (weak)AAAEmployeeMO *employee;
@end
swift
class DetailViewController:UIViewController {
weak varemployee: AAAEmployeeMO?
}
注意
无论何时你在应用程序中传递NSManagedObject
引用,最好将它们设定为weak引用属性。这个防止当NSManagedObject
被删除时view controller为这个已经不存在的对象留下一个野引用。当这个属性被声明为weak时,如果对象被删除,他会自动被设置为nil。
接下来你实现方法prepareForSegue:sender:
来传递合适的NSManagedObject
实例
objc
#define CellDetailIdentifier @"CellDetailIdentifier"
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
id destination= [segue destinationViewController];
if ([[segueidentifier] isEqualToString:CellDetailIdentifier]){
NSIndexPath *indexPath= [[self tableView] indexPathForSelectedRow];
id selectedObject= [[self fetchedResultsController] objectAtIndexPath:indexPath];
[destinationsetEmployee:selectedObject];
return;
}
}
swift
let CellDetailIdentifier ="CellDetailIdentifier"
override funcprepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case CellDetailIdentifier:
let destination =segue.destinationViewController as! DetailViewController
let indexPath =tableView.indexPathForSelectedRow!
let selectedObject =fetchedResultsController.objectAtIndexPath(indexPath)as! AAAEmployeeMO
destination.employee =selectedObject
default:
print("Unknown segue:\(segue.identifier)")
}
}
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.