Created
August 30, 2017 09:11
-
-
Save SuperShinyEyes/063ebf9ad64f8fc4520dde74a03f2963 to your computer and use it in GitHub Desktop.
Save&Load Data locally in a persistent way using Realm
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
@UIApplicationMain | |
class AppDelegate: UIResponder, UIApplicationDelegate { | |
var window: UIWindow? | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
// Override point for customization after application launch. | |
window = UIWindow(frame: UIScreen.main.bounds) | |
window?.rootViewController = UINavigationController(rootViewController: ViewController(style:.plain)) | |
window?.makeKeyAndVisible() | |
return true | |
} | |
} | |
// | |
// ViewController.swift | |
// ToDoWithRealm | |
// | |
// Created by YOUNG on 30/08/2017. | |
// Copyright © 2017 YOUNG. All rights reserved. | |
// https://realm.io/docs/swift/latest/ | |
import UIKit | |
import RealmSwift | |
final class TaskList: Object { | |
@objc dynamic var text = "" | |
@objc dynamic var id = "" | |
let items = List<Task>() | |
override static func primaryKey() -> String? { | |
return "id" | |
} | |
} | |
final class Task: Object { | |
@objc dynamic var text = "" | |
@objc dynamic var completed = false | |
} | |
class ViewController: UITableViewController { | |
var items = List<Task>() | |
var notificationToken: NotificationToken! | |
var realm: Realm! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
setupUI() | |
items.append(Task(value: ["text": "My First Task"])) | |
setupRealm() | |
// loadExistingTasks() | |
} | |
func setupUI() { | |
title = "My Task" | |
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") | |
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add)) | |
} | |
func setupRealm() { | |
DispatchQueue.main.async { | |
do { | |
self.realm = try Realm() | |
if self.realm.objects(TaskList.self).count == 0 { | |
try! self.realm.write { | |
self.realm.add(TaskList()) | |
} | |
} | |
func updateList() { | |
if self.items.realm == nil, let list = self.realm.objects(TaskList.self).first { | |
self.items = list.items | |
} else { | |
print("self.items.realm: \(self.items.realm)") | |
print("self.realm.objects(TaskList.self).count: \(self.realm.objects(TaskList.self).count)") | |
print("items not set") | |
} | |
self.tableView.reloadData() | |
} | |
updateList() | |
self.notificationToken = self.realm.addNotificationBlock{ _,_ in updateList()} | |
} catch { | |
print("Couldn't load Realm") | |
} | |
} | |
} | |
func loadExistingTasks() { | |
do { | |
self.realm = try Realm() | |
if self.items.realm == nil, let list = self.realm.objects(TaskList.self).first { | |
self.items = list.items | |
} | |
self.tableView.reloadData() | |
} catch { | |
print("Couldn't load Realm") | |
} | |
} | |
deinit { | |
notificationToken.stop() | |
} | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return items.count | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) | |
let item = items[indexPath.row] | |
cell.textLabel?.text = item.text | |
cell.textLabel?.alpha = item.completed ? 0.5 : 1 | |
return cell | |
} | |
@objc func add() { | |
let alertController = UIAlertController(title: "New Task", message: "Enter Task Name", preferredStyle: .alert) | |
var alertTextField: UITextField! | |
alertController.addTextField { textField in | |
alertTextField = textField | |
textField.placeholder = "Task Name" | |
} | |
alertController.addAction(UIAlertAction(title: "Add", style: .default) { | |
_ in | |
guard let text = alertTextField.text, !text.isEmpty else { return } | |
let items = self.items | |
try! items.realm?.write { | |
items.insert(Task(value: ["text": text]), at: items.filter("completed = false").count) | |
} | |
}) | |
present(alertController, animated: true, completion: nil) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment