Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Created June 27, 2015 08:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chunkyguy/727b42a700f2ff46c366 to your computer and use it in GitHub Desktop.
Save chunkyguy/727b42a700f2ff46c366 to your computer and use it in GitHub Desktop.
MVVM for UITableView
import UIKit
struct Album {
let title: String
}
class SwiftAlbumsTableViewController: UITableViewController {
@IBOutlet weak private var activityIndicator: UIActivityIndicatorView!
// THIS IS THE DATA SOURCE
private var viewAlbums = [Album]()
// THIS IS THE DATA
var albums: [Album]? {
set {
if let albums = albums {
// populate data as soon we have it
viewAlbums = albums
tableView.reloadData()
}
}
get {
// empty means no data
if viewAlbums.isEmpty {
return nil
} else {
return viewAlbums
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchAlbums()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// so clean!
return viewAlbums.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("albumCell", forIndexPath: indexPath) as! UITableViewCell
// no optionals to think of!
let album = viewAlbums[indexPath.row]
cell.textLabel?.text = album.title
return cell
}
}
// MARK: API Methods
private extension SwiftAlbumsTableViewController {
func fetchAlbums() {
activityIndicator.startAnimating()
// fetch data assynchronously via your API
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))),
dispatch_get_main_queue())
{ [weak self] in
// mimicking data from the API
self?.albums = [Album(title: "1989"), Album(title: "Fearless"), Album(title: "Red"), Album(title: "Speak Now")]
// restore UI
self?.activityIndicator.stopAnimating()
}
}
}
@kinwahlai
Copy link

interesting idea to split the "data source" into 2 parts.

i have a question here, in what situation, we will reach the code at Line #26?

Wouldn't it ok to just return the empty viewAlbums?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment