Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM CoreData FetchedReusltsController

I am trying to start using MVVM with Objective-c but I get some problems with CoreData. I don't know who should handle the fetchedResultsControllerDelegate methods. The viewModel or the viewController?

I think that the viewModel should handle it, but I see too much code to do the same.

like image 238
croigsalvador Avatar asked Jun 10 '16 11:06

croigsalvador


People also ask

Is MVVM good for SwiftUI?

ViewModel is bad and wrong with SwiftUI If you find the MVVM pattern in SwiftUI troublesome or not so useful in your implementation, it may be because the MVVM design pattern does not fit the characteristics of SwiftUI. Until now, iOS application development has often employed the MVVM architecture.

When should I use Core Data?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.

What is NSFetchresultcontroller?

A controller that you use to manage the results of a Core Data fetch request and to display data to the user.

What is Core Data database?

Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.


1 Answers

Let's say you have an edit button in a view. Edit button is hidden when there are no objects in fetchResultsController and you want to show it when any objects are added.

If you implement NSFetchedResultsControllerDelegate in viewController:

  • ViewController gets notifications about changes of model
  • ViewController must notify ViewModel that something happened with the model
  • ViewModel has to change value of the editButtonShown property
  • ViewModel must notify the viewController to update the view

If you implement NSFetchedResultsControllerDelegate in viewModel:

  • model notifies the viewModel about the change
  • viewModel changes the editButtonShown property and sends notification to viewController

If you implement these methods in viewController then it gets reference to the model and this should not happened in MVVM

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath

I think that correct solution is to implement the NSFetchedResultsControllerDelegatein ViewModel. Then you should have similar protocol to notify the viewController to update the view, but it should work with viewModels, not with the models

like image 79
crinos Avatar answered Oct 13 '22 05:10

crinos