第一步导入第三方库
不知道为什么导入最新的第三方库,会存在找不到realm的情况,这里我们就直接导入特定版本的
pod 'RealmSwift', '3.13.1'
一般如果不设置存储的数据库地址的话,会自动存储到沙盒文件的document下,在这里我们自己创建并指定地址.
/// 配置数据库
func configRealm() {
/// 如果要存储的数据模型属性发生变化,需要配置当前版本号比之前大
let dbVersion : UInt64 = 2
let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
let dbPath = docPath.appending("/defaultDB.realm")
let config = Realm.Configuration(fileURL: URL.init(string: dbPath), inMemoryIdentifier: nil, syncConfiguration: nil, encryptionKey: nil, readOnly: false, schemaVersion: dbVersion, migrationBlock: { (migration, oldSchemaVersion) in
}, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil)
Realm.Configuration.defaultConfiguration = config
Realm.asyncOpen { (realm, error) in
if let _ = realm {
print("Realm 服务器配置成功!")
}else if let error = error {
print("Realm 数据库配置失败:\(error.localizedDescription)")
}
}
}
初始化对象
class User: Object {
///可以存储的类型有很多
@objc dynamic var phone = ""
@objc dynamic var name = ""
@objc dynamic var header: Data = Data()
@objc dynamic var password = ""
@objc dynamic var isLogin = false
///User里包含另外一个对象数组
let gameList = List<Game>()
///设置了关键字,那么就不能创建重复的User对象 phone 值相同
///如果相同会直接崩溃
override static func primaryKey() -> String? {
return "phone"
}
///获取realm地址
class func getDB() -> Realm {
let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
let dbPath = docPath.appending("/defaultDB.realm")
print(docPath.appending("/defaultDB.realm"))
/// 传入路径会自动创建数据库
let defaultRealm = try! Realm(fileURL: URL.init(string: dbPath)!)
return defaultRealm
}
///存到本地realm,
public class func insertStudent(by student : User) -> Void {
let defaultRealm = self.getDB()
try! defaultRealm.write {
///这里一定要用update,如果User对象设置了关键字的话
///不然会因为关键字相同, 会直接崩溃
///这样写,直接调用这个User的方法,可以实现没有创建,创建了就更新的效果
defaultRealm.add(student, update: true)
}
print(defaultRealm.configuration.fileURL ?? "")
}
///给User里面添加Game
func insertGame(by game: Game){
let defaultRealm = User.getDB()
///查询语句,sql
let some = defaultRealm.objects(Game.self).filter("gameId contains '\(game.gameId)' AND userId contains '\(self.phone)'")
///注意,realm的对象,你可以赋值, 使用
///但是你如果一旦要改变,那么 必须在write里面来改变
try! defaultRealm.write {
///针对Game里面存在关键字的情况,因为realm如果一旦设置了关键字,就没办法重复添加
///如果存在了那么就只能修改,数组里面没有找到可以更新game的方法,所以就自己写了更新
if some.count > 0 {
let temp = some.first!
temp.opponent = game.opponent
temp.place = game.place
temp.date = game.date
temp.startTime = game.startTime
temp.remark = game.remark
temp.userId = game.userId
}else{
self.gameList.append(game)
}
}
print(defaultRealm.configuration.fileURL ?? "")
}
}
class Game: Object {
@objc dynamic var gameId = ""
@objc dynamic var opponent = ""
@objc dynamic var place = ""
@objc dynamic var date = ""
@objc dynamic var startTime = ""
@objc dynamic var remark = ""
@objc dynamic var userId = ""
///没有选,1 参加,2 请假
@objc dynamic var isUserJoin = "0"
///设置关键字
override static func primaryKey() -> String? {
return "gameId"
}
///设置他的父类,和父类gameList 关联
let owners = LinkingObjects(fromType: User.self, property: "gameList")
}