Core Data做用户信息存储 -Swift

大部分APP多会涉及到用户信息,包括Token,头像,电话,昵称等存储,在APP不同部分去掉用,根据每个开发的个人爱好不同,用的存储方式也不同,如:1.XML属性列表(plist)归档

2.Preference(偏好设置)

3.NSKeyedArchiver归档(NSCoding)

4.SQLite3

5.Core Data

可能大家对1,2,3使用比较多笔者之前开发,对于用户信息,一般习惯用NSKeyedArchiver,不过最近一直在对之前OC代码的项目用Swift重构,在写到用户信息存储时,就是想换个方式写一写,多学点东西总是好的嘛..其实是比较简单,大家对Core Data都不陌生,只是简单把自己写的一个Demo贴出来,就当练练手,熟悉熟悉语法....

1.建立模型

Core Data做用户信息存储 -Swift_第1张图片
Snip20171011_1.png

2.创建增删改查
先创建一个UserInfo用户信息管理类

var token:String!
var header_img:String!
var isselecttopic:String!
var nick_name:String!
var user_name:String!
var username:String!

/*
 存储用户信息
 messageDic 将用户信息写成字典传入即可存储
 */
class func saveDataFromSQL(messageDic:Dictionary){
    UserInfo.deleteDataFromSQL()
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObectContext = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "UserMode", in: managedObectContext)
    let person = NSManagedObject(entity: entity!, insertInto: managedObectContext)
    for r in messageDic{
        person.setValue(r.value, forKey: r.key)
    }
    do {
        try managedObectContext.save()
    } catch  {
        fatalError("无法保存")
    }
}

//查询用户信息
func getDataFromSQL() -> UserInfo{
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObectContext = appDelegate.persistentContainer.viewContext
    let fetchReq = NSFetchRequest(entityName: "UserMode")
    do {
        let fetchResult = try managedObectContext.fetch(fetchReq)
        for info in fetchResult {
            token = info.token
            header_img = info.header_img
            isselecttopic = info.isselecttopic
            nick_name = info.nick_name
            user_name = info.user_name
            username = info.username
        }
    } catch{
        print("查询失败")
    }
    return self
}

//删除用户信息
class func deleteDataFromSQL() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObectContext = appDelegate.persistentContainer.viewContext
    //UserMode
    let fetchReq = NSFetchRequest(entityName: "UserMode")
    do {
        let fetchResult = try managedObectContext.fetch(fetchReq)
        for info in fetchResult {
            managedObectContext.delete(info)
        }
    } catch{
        print("查询失败")
    }
}


/*
 修改用户信息
 changeMessage: key=原参数 value=要修改的参数
 */
class func changeDataFromSQL(changeMessage:Dictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObectContext = appDelegate.persistentContainer.viewContext
    let fetchReq = NSFetchRequest(entityName: "UserMode")
    do {
        let fetchResult = try managedObectContext.fetch(fetchReq)
        for info in fetchResult {
            for r in changeMessage {
                if r.key == info.token {
                    info.token = r.value
                }else if r.key == info.header_img {
                    info.header_img = r.value
                }else if r.key == info.isselecttopic {
                    info.isselecttopic = r.value
                }else if r.key == info.nick_name {
                    info.nick_name = r.value
                }else if r.key == info.user_name {
                    info.user_name = r.value
                }else if r.key == info.username {
                    info.username = r.value
                }
            }
        }
    } catch{
        print("查询失败")
    }
}

3.调用

override func viewDidLoad() {
    //super.viewDidLoad()
    let userMessgae : Dictionary = ["header_img":"www.dongjingHot.png", "isselecttopic":"1", "nick_name":"苍井空", "token":"f9e2K/lyNoDATeIpVn31rnGpbxi6rdv/MoxEO9Bj2JqU33aPfvBPaI/sJgBN7P776Z66FNSa/p23aP5zFQ1pwJCrTvTLN/hCs3WLpB5/","user_name":"185****"]
   
    //存储用户信息
    UserInfo.saveDataFromSQL(messageDic: userMessgae)
    
    //查询用户信息
    print(UserInfo().getDataFromSQL().user_name)
   
    //修改用户信息
    UserInfo.changeDataFromSQL(changeMessage: [UserInfo().getDataFromSQL().user_name:"18"])
    print(UserInfo().getDataFromSQL().user_name)
    
    //删除用户信息
    UserInfo.deleteDataFromSQL()
    print(UserInfo().getDataFromSQL().token)
}

备注:随手写的,有问题欢迎大家指正。

你可能感兴趣的:(Core Data做用户信息存储 -Swift)