Last active
March 22, 2016 05:52
-
-
Save moflo/253231bba96dadfc3f85 to your computer and use it in GitHub Desktop.
RealmORM, realm.io ORM in Swift 2.0 with simple CoreData like NSFetchController features, sorting Results<object> by a key
This file contains 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
// | |
// RealmORM.swift | |
// | |
// Copyright © 2016 Mobile Flow LLC. All rights reserved. | |
// | |
import UIKit | |
import Realm | |
import RealmSwift | |
class RealORMFetchObject { | |
var sections = Dictionary<String, Array<RealmORM>>() | |
var sortedSections = [String]() | |
let managedObjectContext : NSObject? = nil | |
let fetchRequest : NSObject? = nil | |
init() { | |
} | |
func reset() { | |
self.sections.removeAll(keepCapacity: true) | |
self.sortedSections.removeAll(keepCapacity: true) | |
} | |
func fetchResultsBySection(realm: Realm, sectionKey: String, classObject: RealmORM.Type) -> Int { | |
self.reset() | |
let objects = classObject.fetchAll(realm) | |
for item in objects { | |
// NOTE: assumes section key type of String, need to refactor for NSDate, Int64, etc. | |
let value :String = (item.valueForKey(sectionKey) ?? "") as! String | |
if self.sections.indexForKey(value) == nil { | |
self.sections[value] = [item] | |
} | |
else { | |
self.sections[value]?.append(item) | |
} | |
} | |
self.sortedSections = Array(self.sections.keys).sort{ $0 < $1 } | |
return self.sortedSections.count | |
} | |
func objectAtIndexPath(indexPath :NSIndexPath) -> RealmORM? { | |
guard sortedSections.count > indexPath.section else { return nil } | |
let tableSection = sections[sortedSections[indexPath.section]] | |
guard tableSection != nil && tableSection!.count > 0 else { return nil } | |
let tableItem = tableSection![indexPath.row] | |
return tableItem | |
} | |
func numberOfRowsInSection(section :Int) -> Int { | |
guard sortedSections.count > section else { return 0 } | |
guard sections.count > 0 else { return 0 } | |
return sections[sortedSections[section]]?.count ?? 0 | |
} | |
} | |
class RealmORM: Object { | |
dynamic var uuid :String = NSUUID().UUIDString | |
dynamic var createdAt = NSDate() | |
func save(realm: Realm) { | |
try! realm.write { | |
realm.add(self) | |
} | |
} | |
class func fetchAll(realm: Realm) -> Results<RealmORM> { | |
return realm.objects(self).sorted("createdAt", ascending: true) | |
} | |
} |
Author
moflo
commented
Mar 22, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment