I am using .xibs and I want to use Core Data. The simplest answer is to define @property
in AppDelegate.h. But I need to fill my model in xml-parser files and I want to fetch data in many controllers. So using [[[UIApplication sharedApplication] delegate] context]
there is so ugly.
Is there any good-looking solution?
2 に答える
サブクラス化されたすべてのオブジェクトにNSManagedObject
もコンテキストがあることに注意してください。Book
(古典的な例)とがあるとしましょうAuthor
。Entitis ofcです。関係 1-n (1 人の著者 - 複数の本) を使用します。
ここで何を達成しようとしているのかはわかりませんが、多くのアプリケーションでは、master-detail-more details - ... viewControllers があります。例に戻ります。
MainViewController がAuthorsViewController
. これは著者の tableView です。著者をタップして、彼が書いた本を見たいとします。したがって、あなたBooksViewController
には1つのモデルプロパティがあります:
@property (strong,nonatomic) Author *author;
さまざまな方法で設定できます。カスタム セッター、セグエから渡す...気にしないでください。これはかなり明白だと確信しています。
ここで素晴らしいのは、これを行った後、すでにコンテキストがBooksViewController
. あなたが書くたびに:
self.author.managedObjectContext
これは正しいコンテキストになります。
したがって、navigationController
アプリがある場合はAppDelegate
、シングルトン クラスまたは mainVC でコンテキストを作成できます。一度だけ呼び出して、そこから呼び出してNSManagedObject
パスします。
この素晴らしいチュートリアルを試すことができます:単一の共有 uimanageddocument を持つコア データ