私は解決するために同様のアイテムに遭遇し、同じものを使用しUIViewController
て両方の操作を行うことになりました。どちらのユース ケースも基本的には同じです。ユーザーは情報を入力してから保存します。データの検証、保存、プレゼンテーションは同じです。モデルオブジェクトがすでに存在するかどうかによってのみ異なります。次の例を検討してください。
.h ファイル:
@interface WHItemViewController : UITableViewController
// This is the only attribute we really need to expose in our header
// so that the presenting view controller can set the model object when editing
@property (nontatomic, retain) WHItem* item;
@end
.m ファイル:
@interface WHItemViewController()
// Other 'private' properties and methods
- (void)didSelectSaveButton:(id)sender;
@end
@implementation WHItemViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (self.item) { // setup the UI with the model object, if present.
self.fooText.text = self.item.foo;
self.barText.text = self.item.bar;
self.bazText.text = self.item.baz;
}
}
- (void)didSelectSaveButton:(id)sender {
if (!self.item) {
WHItem* item = nil;
// create a new instance from your managed object context
// and set it to the item property
self.item = item;
}
self.item.foo = self.fooText.text;
self.item.bar = self.barText.text;
self.item.baz = self.bazText.text
NSError* error = nil;
[WHDataAccess sharedInstance].managedObjectContext save:&error];
// Error handling, etc.
}
// Other methods
@end
このビュー コントローラーの唯一の目的は、モデル オブジェクト データを編集および保存するためのプレゼンテーションを作成することです。