• iOS CoreData使用笔记


    1.创建CoreData

    2.创建对应实体类

    //
    //  UserInfo.swift
    //  
    //
    //  Created by Fran on 15/7/31.
    //
    //
    
    let APP_CORE_DATA_ENTITY_NAME_USERINFP = "UserInfo"
    import Foundation import CoreData @objc(UserInfo) class UserInfo: NSManagedObject { @NSManaged var userId: String @NSManaged var name: String @NSManaged var portraitUri: String }

      // 注意代码中的 @obj(ClassName) 必须要写, 属性前的 @NSManaged 也是不可或缺的

    3. 操作类(增删改查)

    //
    //  UserInfoManager.swift
    //  ECExpert
    //
    //  Created by Fran on 15/7/31.
    //  Copyright (c) 2015年 Fran. All rights reserved.
    //
    
    import UIKit
    
    class UserInfoManager: NSObject {
        
        private var managedObjectContext: NSManagedObjectContext!
        private var managedObjectModel: NSManagedObjectModel!
        private var persistentStoreCoordinator: NSPersistentStoreCoordinator!
        
        private override init() {
            super.init()
        }
        
        class func shareManager() -> UserInfoManager{
            struct SingleManager{
                static var token: dispatch_once_t = 0
                static var singleManager: UserInfoManager!
            }
            
            dispatch_once(&SingleManager.token, { () -> Void in
                let manager = UserInfoManager()
                
                // 创建数据库
                // 1. 实例化数据模型(将所有定义的模型都加载进来)
                // merge——合并
                manager.managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil)
                
                // 2. 实例化持久化存储调度,要建立起桥梁,需要模型
                manager.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: manager.managedObjectModel)
                
                // 3. 添加一个持久化的数据库到存储调度
                // 3.1 建立数据库保存在沙盒的URL
                let basicPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
                let filePath = basicPath!.stringByAppendingString("/").stringByAppendingString(APP_PATH_CHAT_USERINFO)
                let url = NSURL(fileURLWithPath: filePath)
                
                // 3.2 打开或者新建数据库文件
                // 如果文件不存在,则新建之后打开
                // 否者直接打开数据库
                do {
                    try manager.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
                    manager.managedObjectContext = NSManagedObjectContext()
                    manager.managedObjectContext.persistentStoreCoordinator = manager.persistentStoreCoordinator
                    SingleManager.singleManager = manager
                } catch let error as NSError {
                    KMLog("(error.localizedDescription)")
                } catch {
                    fatalError()
                }
            })
            
            return SingleManager.singleManager
        }
        
        func queryUserInfoById(userId: String) -> NSMutableArray{
            let array = NSMutableArray()
            let predicate = NSPredicate(format: "userId = '(userId)'")
            let request = NSFetchRequest(entityName: APP_CORE_DATA_ENTITY_NAME_USERINFO)
            request.predicate = predicate
            
            let rs = try? managedObjectContext.executeFetchRequest(request)
            if rs != nil{
                for u in rs!{
                    KMLog("(u.userId) (u.name) (u.portraitUri)")
                    array.addObject(u)
                }
            }
            
            return array
        }
        
        func addUserInfo(userId: String, name: String, portraitUri: String) -> Bool{
            let queryArray = queryUserInfoById(userId)
            if queryArray.count == 0{
                let userInfo = NSEntityDescription.insertNewObjectForEntityForName(APP_CORE_DATA_ENTITY_NAME_USERINFO, inManagedObjectContext: managedObjectContext) as! UserInfo
                userInfo.userId = userId
                userInfo.name = name
                userInfo.portraitUri = portraitUri
                
                do {
                    try managedObjectContext.save()
                    return true
                } catch _ {
                    return false
                }
            }else{
                return updateUserInfo(userId, updateDic: ["name": name, "portraitUri": portraitUri])
            }
        }
        
        func removeUserInfoById(userId: String) -> Bool{
            var result = false
            let request = NSFetchRequest(entityName: APP_CORE_DATA_ENTITY_NAME_USERINFO)
            request.predicate = NSPredicate(format: "userId = '(userId)'")
            
            let rs = try? managedObjectContext.executeFetchRequest(request)
            if rs != nil{
                for u in rs!{
                    KMLog("(u.userId) (u.name) (u.portraitUri)")
                    managedObjectContext.deleteObject(u as! NSManagedObject)
                }
                do {
                    try managedObjectContext.save()
                    result = true
                } catch _ {
                    result = false
                }
            }
            
            return result
        }
        
        func updateUserInfo(userId: String, updateDic: NSDictionary!) -> Bool{
            var result = false
            let request = NSFetchRequest(entityName: APP_CORE_DATA_ENTITY_NAME_USERINFO)
            request.predicate = NSPredicate(format: "userId = '(userId)'")
            
            if updateDic != nil && updateDic.count > 0{
                let rs = try? managedObjectContext.executeFetchRequest(request)
                if rs != nil{
                    for u in rs!{
                        KMLog("(u.userId) (u.name) (u.portraitUri)")
                        for (key, value) in updateDic{
                            u.setValue(value, forKey: key as! String)
                        }
                    }
                    
                    do {
                        try managedObjectContext.save()
                        result = true
                    } catch _ {
                        result = false
                    }
                }
            }
            
            return result
        }
        
    }
    

      

  • 相关阅读:
    清除页面广告?身为前端,自己做一款简易的Chrome扩展吧
    Nginx 引入线程池,提升 9 倍性能
    调试时屏蔽JavaScript库代码 –Chrome DevTools Blackbox功能介绍
    收集的React.JS资料
    谈谈 React.js 的核心入门知识
    同时包含字母和数字的正则表达式
    Word2010撤销按钮失效,Ctrl+Z失效解决办法
    大数据于产业金融领域的运用究竟如何很好的实现
    HTTP 错误 500.19
    WindowsServer2012桌面图标设置
  • 原文地址:https://www.cnblogs.com/FranZhou/p/5102633.html
Copyright © 2020-2023  润新知