Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

ios - ViewModel for UITableViewCell: Database operations "allowed"?

I am trying to understand how to correctly use the MVVM pattern in iOS. Lets assume we have a music player app with a playlist like in the following sketch:

enter image description here

I have a PlaylistViewController and a PlaylistViewModel. Furthermore the cells (SongTableViewCell) have a view model SongCellViewModel which holds the data (song name,..). If the user presses the X button on the TableViewCell I have to delete the song from the database. The cell is calling the following function in the SongCellViewModel:

func deleteSongFromPlaylist() {
   DatabaseService.shared.deleteSong(self.song)
}

My question: Is it good to do it that way? It doesn't feel right to initiate database operations in the view model of the TableViewCell.

question from:https://stackoverflow.com/questions/65918432/viewmodel-for-uitableviewcell-database-operations-allowed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suggest moving such operations to PlaylistViewModel and do all operations from there. It also simplifies implementation of later improvements like showing activity indicator if needed or reloading certain cells or views from there.

I think that SongCellViewModel should have a actionBlock which will take enum with associated values - for example .select(song) .delete(song) - and this way you can easily communicate between PlaylistViewModel and SongCellViewModel.

One more suggestion is to use Dependency Injections instead of using shared for all type of services.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...