Created
June 27, 2015 08:28
-
-
Save chunkyguy/727b42a700f2ff46c366 to your computer and use it in GitHub Desktop.
MVVM for UITableView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?