开发者

Core data delegate saving pattern

开发者 https://www.devze.com 2023-04-10 20:09 出处:网络
I am using CoreData in iOS. I have a modal AddViewController, with a RootViewController as the delegate.

I am using CoreData in iOS. I have a modal AddViewController, with a RootViewController as the delegate.

Should I do the saving of the managed object context in the root controller, or in the actual modal controller itself?

I am seeing examples of passing the data back to the rootViewController, but can't see how this will work with data validation failures, or more complex scenarios that need th开发者_JAVA百科e managed object context.

// AddViewController.m

- (void)save
{
  [[self delegate] controller:(id)controller didFinishWithSave:(BOOL)save withName(NSString *)name;
}

// RootViewController.m

- (void)controller:(id)controller didFinishWithSave:(BOOL)save
{
  if (save)
  {
    // save context
  }
  [self dismissModalViewControllerAnimated:YES];
}

As at the moment I am dismissing the modal using the delegate protocol. Any advice on the best practices? Thanks


I know this is a little late, but for others who come across this, I'd add a little more to Levend's answer.

Yes, you should have a separate manager class to handle the operations (possibly the class itself).

I would think that if your modal needed to handle validations, before calling on the delegate, it would validate the object. If it had an error, you could handle it right there. If it passed validations, then you could pass the valid object to the delegate. Thus the delegate can make the assumption that any object that is getting passed to it is a valid one.

As to which class you should save it, I think that is just a preference thing. But I would suggest you have a save method in the core data model itself.

Something I came across recently is the mogenerator which is supposed to help with managing CoreData classes. I haven't tired it yet, but it sounds good.


From an architecture point of view, you should create a separate manager class responsible for core data operations. From technical point of view, it isnt matter where you save(root, or modal VC) as long as you do it on the same thread where the data origins.


With MVC in mind I would let the M(odel) perform saving of the context as well as fetching data from it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号