我使用Apple提供的默認模板和Core Data(managedObjectContext位於AppDelegate中)。起初,我在每個需要使用managedObjectContext的類中都包含了appdelegate.h,但是我看到這不是正確的方法。蘋果公司表示最好只將上下文傳遞給其他需要它的類,所以我最終這樣做了。事情是,它看起來有點像我這樣做的「駭客」,我想知道是否有更好的選擇,或者我的解決方案是正確的。將managedObjectContext(核心數據)傳遞給其他類,是否正確完成?
我的應用程序是目前這樣的設置(這是我的故事板的SS):
所以我的根窗口是一個的UITabBarController,每個選項卡是指向多的UITableViewController/UIViewController的一個UINavigationController。
以下是我在我的appDelegate到managedObjectContext實例傳遞給2個選項卡:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *rootViewController;
UINavigationController *navigationController;
ItemsTableViewController *itemsTableViewController;
// Get the root window (UITabBarController)
rootViewController = (UITabBarController *)self.window.rootViewController;
// Get the second item of the UITabBarController
navigationController = [[rootViewController viewControllers] objectAtIndex:1];
// Get the first item of the UINavigationController (ItemsTableViewController)
itemsTableViewController = [[navigationController viewControllers] objectAtIndex:0];
itemsTableViewController.managedObjectContext = self.managedObjectContext;
// Get the third item of the UITabBarController (again ItemsTableViewController)
navigationController = [[rootViewController viewControllers] objectAtIndex:2];
// Get the first item of the UINavigationController (ItemsTableViewController)
itemsTableViewController = [[navigationController viewControllers] objectAtIndex:0];
itemsTableViewController.managedObjectContext = self.managedObjectContext;
return YES;
}
一切運作良好,但不必調用多次objectAtIndex以獲得正確的視圖控制器看起來咩...
任何人都可以作爲更好的解決方案嗎?
謝謝!
Huum,UITabViewController的子類看起來很有趣。同時我也要確保書籤MagicalRecord,但由於它是我的第一個使用核心數據的項目,所以我寧願不使用框架來真正獲得所有的概念:)除非你告訴我MagicalRecord確實是必須的:P – allaire 2012-01-17 01:46:34
@allaire我實際上會按照你所說的去做,並首先熟悉CoreData。一旦你感到舒服,並知道發生了什麼,那麼MagicalRecord是必須的:) – Rog 2012-01-17 03:22:50
我可能會補充說,傳遞上下文的「最正確」方式是通過「prepareForSegue:」。通過添加一個屬性到標籤欄控制器,您正在簽署的事實是,您的應用程序將始終有一個對標籤欄控制器的引用,所以如果您決定在將來更改它,這將是一個痛苦。 – Rog 2012-01-17 03:24:59