Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelbeek/9658a0a6d38c5a6a63c9 to your computer and use it in GitHub Desktop.
Save samuelbeek/9658a0a6d38c5a6a63c9 to your computer and use it in GitHub Desktop.
Awesome local storage usage with Realm in Swift
// this code does work, but since it's from a 'secret' project, I can't display
// the other code. Implement it in your own project, it'll work.
//
// LOCAL.swift
// Wildcard
//
// Created by Samuel Beek on 08/07/15.
// Copyright (c) 2015 Wildcard. All rights reserved.
//
import RealmSwift
protocol Networking {
static var collected : [User] {get set}
static var matched : [User] {get set}
}
struct Local : Networking {
static var collected : [User] {
get {
let collectedArray = Realm(path: Constants.Realms.collectedPath).objects(User)
var localArray : [User] = []
for user in collectedArray {
localArray.append(user)
}
log("localArray:", localArray.count)
return localArray
}
set(array) {
let realm = Realm(path: Constants.Realms.collectedPath)
for user in array {
realm.write {
realm.add(user, update: true)
}
}
}
}
static var matched : [User] {
get {
let matchedArray = Realm(path: Constants.Realms.matchesPath).objects(User)
var localArray : [User] = []
for user in matchedArray {
localArray.append(user)
}
return localArray
}
set(array) {
let realm = Realm(path: Constants.Realms.matchesPath)
for user in array {
realm.write {
realm.add(user, update: true)
}
}
}
}
static func delete(){
let matches = Realm(path: Constants.Realms.matchesPath)
let collected = Realm(path: Constants.Realms.collectedPath)
matches.write {
matches.deleteAll()
}
collected.write {
collected.deleteAll()
}
}
}
// tableview content
self.tableArray = Local.collected
self.tableView.reloadData()
API.getCollected { userArray in
// Use accessKey however you'd like here
Local.collected = userArray
self.tableView.reloadData()
self.loadingIndicator.removeFromSuperview()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment