Skip to content

Instantly share code, notes, and snippets.

@jackyshan
Last active May 29, 2017 01:28
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 jackyshan/ae8a7be905b8e568e6c91070c5ff6d99 to your computer and use it in GitHub Desktop.
Save jackyshan/ae8a7be905b8e568e6c91070c5ff6d99 to your computer and use it in GitHub Desktop.
realm基础数据封装代码,实现增删查改
//
// DBBaseObject.swift
// DianZiCheng
//
// Created by jackyshan on 2017/5/28.
// Copyright © 2017年 jackyshan. All rights reserved.
//
import UIKit
class DBBaseObject: Object {
dynamic var note1: String?//备份
dynamic var note2: String?//备份
func add() {//增
let realm = try! Realm()
try! realm.write {
realm.add(self)
}
}
func delete() {//删
let realm = try! Realm()
try! realm.write {
realm.delete(self)
}
}
static func query<T>(_ type: T.Type, _ filterStr: String? = nil) -> Results<T> {//查
let realm = try! Realm()
if let str = filterStr {
return realm.objects(type).filter(str)
}
else {
return realm.objects(type)
}
}
//多线程查询
static func query<T>(_ type: T.Type, _ filterStr: String? = nil, block:@escaping ((_ results: Results<T>)->Void)) {
DispatchQueue(label: "background").async {
let realm = try! Realm()
if let str = filterStr {
let objects = realm.objects(type).filter(str)
block(objects)
}
else {
let objects = realm.objects(type)
block(objects)
}
}
}
static func update(_ block: (() throws -> Swift.Void)) {//改
let realm = try! Realm()
try! realm.write(block)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment