//
// TSMessageState.swift
// N-Students
//
// Created by 王木木 on 16/8/22.
// Copyright © 2016年 E-edu Space. All rights reserved.
//
/// 更详细内容请参考 http://www.hangge.com/blog/cache/detail_891.html
import Foundation
import RealmSwift
/** 消息免打扰开关状态 */
class TSMessageState: Object {
// true 打开 false关闭
dynamicvar messageState: Bool = true
/// 用户code
dynamicvar userCode: String =""
}
extension TSMessageState{
/*!
增加数据 && 删除数据
*/
func setMessageType(model:Bool){
/// 创建Realm对象
let realm =try! Realm()
/// 获取对象为 TSMessageState的所有数据
let items = realm.objects(TSMessageState)
/// 获取当前用户code
let code =TSUserManager.sharedInstance().user?.basic?.openId
/*!
* 如果本地有数据存在
*/
if items.count >0 {
/// 查询语句 查询userCode 为code的 TSMessageState对象
let predicate =NSPredicate(format: "userCode = %@", code!)
/// 获取查询到的对象
let consumeItems = realm.objects(TSMessageState).filter(predicate)
// 在事务中删除对象
try! realm.write {
/*!
* 删除这些数据
*/
realm.delete(consumeItems)
}
}
/// 创建 TSMessageState对象
let message =TSMessageState()
/*!
* 给新对象赋值
*/
message.messageState = model
message.userCode = code!
//在事务中保存对象
try! realm.write {
realm.add(message)
}
}
/*!
查询数据
*/
func getMessageType()->(Bool){
let model =TSMessageState()
let realm =try! Realm()
let items = realm.objects(TSMessageState)
let code =TSUserManager.sharedInstance().user?.basic?.openId
if items.count >0 {
let predicate =NSPredicate(format: "userCode = %@", code!)
let consumeItems = realm.objects(TSMessageState).filter(predicate)
if consumeItems.count >0 {
return consumeItems[0].messageState
}
}
return model.messageState
}
/*!
* 修改数据
*/
func updateSingInData(bool:Bool){
let realm =try! Realm()
let items = realm.objects(TSMessageState)
let code =TSUserManager.sharedInstance().user?.basic?.openId
if items.count >0 {
let predicate =NSPredicate(format: "userCode = %@", code!)
let consumeItems = realm.objects(TSMessageState).filter(predicate)
if consumeItems.count >0 {
let model = consumeItems[0]
/*!
* 在事务中更新对象属性
*/
try! realm.write {
model.messageState = bool
}
}
}
}
}