Core Data很好的整合了Xcode的Strroyboards的功能知市,你可以用它來創(chuàng)建UI襟士。這種集成允許你利用依賴注入模式(dependency injection)。依賴注入是一個(gè)控件的反轉(zhuǎn);它允許框架使用者通過引用傳遞到調(diào)用對(duì)象來控制流妇汗。依賴注入模式(dependency injection)是用于Cocoa開發(fā)的首選模式之一,尤其是iOS Cocoa的開發(fā)说莫。
Integrating Core Data with a Storyboard Segue
Core Data和Storyboard一個(gè)復(fù)雜的集成點(diǎn)是:表格視圖中顯示大量的數(shù)據(jù)對(duì)象過度到介紹其中一個(gè)項(xiàng)目細(xì)節(jié)的子視圖控制器杨箭。不使用Storyboard時(shí),是通過重寫表格視圖代理(UITableViewDelegate)的tableView:didSelectRowAtIndexPath:的方法實(shí)現(xiàn)储狭。然而在Storyboard里互婿,這種方法不應(yīng)該不使用捣郊,過度的處理應(yīng)該在 prepareForSegue:sender:的方法里實(shí)現(xiàn)。
下面是演示如何將Core Data和Storyboard segue集成慈参,組主視圖控制器是一個(gè)員工的表格名單呛牲,單選中一個(gè)表格中其中一個(gè)員工時(shí),會(huì)跳轉(zhuǎn)呈現(xiàn)出一個(gè)員工詳細(xì)的信息視圖驮配。這里假設(shè)視圖控制器在segue里面有接收選擇的屬性娘扩。
Objective-C
@interface DetailViewController : UIViewController
@property (weak) AAAEmployeeMO *employee;
@end
Swift
class DetailViewController: UIViewController {
weak var employee: EmployeeMO?
}
注:
在應(yīng)用程序里無論那里通過NSManagedObject時(shí),使用弱引用(weak)聲明他們壮锻。當(dāng)NSManagedObject被刪除并且留下一個(gè)懸掛引用一個(gè)不存在的對(duì)象時(shí)琐旁,有助于保護(hù)視圖控制器(view controller)。當(dāng)屬性(property)聲明為弱引用(weak)時(shí)猜绣,并且對(duì)象被刪除時(shí)灰殴,它將自動(dòng)設(shè)置為nil。
下一步掰邢,在主視圖控制器的prepareforsegue:方法中牺陶,通過適當(dāng)?shù)腘SManagedObject實(shí)例,然后實(shí)現(xiàn)方法尸变。
Objective-C
#define CellDetailIdentifier @"CellDetailIdentifier"
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
id destination = [segue destinationViewController];
if ([[segue identifier] isEqualToString:CellDetailIdentifier]) {
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
id selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
[destination setEmployee:selectedObject];
return;
}
}
Swift
let CellDetailIdentifier = "CellDetailIdentifier"
override func prepareForSegue(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! EmployeeMO
destination.employee = selectedObject
default:
print("Unknown segue: \(segue.identifier)")
}
}
在segue檢索過segue的標(biāo)識(shí)符(需要在storyboard中的每個(gè)segue都是獨(dú)特的)后义图,就可以安全的取得目標(biāo)(destination)視圖控制器(view Controller),并將選中的員工實(shí)例的引用傳遞給目標(biāo)(destination)視圖控制器(view Controller)召烂。然后碱工,目標(biāo)(destination)視圖控制器(view Controller)在其生命周期的加載部分有可用的數(shù)據(jù)引用,并顯示其相關(guān)的數(shù)據(jù)奏夫。這是依賴注入(dependency injection)怕篷,父視圖控制器決定將哪一個(gè)員工實(shí)例交給目標(biāo)(destination)視圖控制器(view Controller)來控制應(yīng)用程序的流程。