Skip to content

Instantly share code, notes, and snippets.

@icanzilb
Created December 15, 2016 13:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save icanzilb/8e20295730f49c6ec6c494ebd5c198a8 to your computer and use it in GitHub Desktop.
Save icanzilb/8e20295730f49c6ec6c494ebd5c198a8 to your computer and use it in GitHub Desktop.
NSBarcelona Realm Demo
class FavoritesTableViewController: UITableViewController {
private var subscription: NotificationToken?
private var messages: Results<Message>?
// MARK: - set up the view controller
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
messages = realm.defaultUser.messages.filter("favorite = true")
subscription = messages?.addNotificationBlock({[weak self] changes in
switch changes {
case .initial:
self?.tableView.reloadData()
case .update(_, let deletions, let insertions, let updates):
self?.tableView.applyChanges(section: 0, deletions: deletions, insertions: insertions, updates: updates)
default: break
}
})
}
// MARK: - table view methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messages![indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: FeedTableViewCell.reuseIdentifier,
for: indexPath) as! FeedTableViewCell
cell.configureWithMessage(message)
return cell
}
}
class Message: Object {
//MARK: - Properties
dynamic var id = ""
dynamic var message = ""
dynamic var name = ""
let photos = List<Photo>()
dynamic var favorite = false
dynamic var timestamp: TimeInterval = Date().timeIntervalSinceReferenceDate
//MARK: - Meta
override static func primaryKey() -> String? {
return "id"
}
override class func indexedProperties() -> [String] {
return ["favorite"]
}
}
extension Realm {
var defaultUser: User {
return objects(User.self).filter("name = 'me'").first ?? setupDefaultUser()
}
func setupDefaultUser() -> User {
let user = User()
let createUser = {[unowned self] in
self.add(user)
self.add(Photo(value: ["url": "me@2x.png"]))
}
if isInWriteTransaction {
createUser()
} else {
try? write(createUser)
}
return user
}
}
import UIKit
private func fromRow(_ section: Int) -> (_ row: Int) -> IndexPath {
return {row in
return IndexPath(row: row, section: section)
}
}
extension UITableView {
func applyChanges(section: Int, deletions: [Int], insertions: [Int], updates: [Int]) {
beginUpdates()
deleteRows(at: deletions.map(fromRow(section)), with: .automatic)
insertRows(at: insertions.map(fromRow(section)), with: .automatic)
reloadRows(at: updates.map(fromRow(section)), with: .none)
endUpdates()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment