Core Data

Core Data是用來(lái)將模型對(duì)象持久化儲(chǔ)存的框架偏形,可以保存XML敏储、atomic、SQLite格式的文件丁侄。這里使用SQLite來(lái)舉例惯雳。在你新建一個(gè)工程的時(shí)候,選擇use Core Data鸿摇,Xcode會(huì)幫你做一些準(zhǔn)備工作石景。在這里一共有這么幾個(gè)東西,持久化儲(chǔ)存文件拙吉,持久化儲(chǔ)存協(xié)調(diào)器潮孽,托管對(duì)象模型,托管對(duì)像上下文筷黔。

  • 一個(gè)托管對(duì)象模型中會(huì)有多個(gè)實(shí)體恩商,這些實(shí)體可以儲(chǔ)存在不同的持久化儲(chǔ)存文件中
  • 一個(gè)持久化儲(chǔ)存協(xié)調(diào)器只能和一個(gè)托管對(duì)象模型相連
  • 一個(gè)或多個(gè)托管對(duì)象上下文通過(guò)訪問(wèn)持久化對(duì)象儲(chǔ)存協(xié)調(diào)器來(lái)訪問(wèn)持久化儲(chǔ)存文件
  • 程序中操作的就是托管對(duì)象上下文

創(chuàng)建實(shí)體

Xcode會(huì)給你創(chuàng)建一個(gè)CoreDataTest.xcdatamodeld文件,這就是你管理你的對(duì)象的地方必逆,新建實(shí)體怠堪,并在實(shí)體里建立你需要的屬性和關(guān)系等揽乱。
建立好之后就可以讓Xcode幫助你生成每個(gè)實(shí)體對(duì)應(yīng)的類了:Editor -> Create NSManagedObject SubClass。對(duì)應(yīng)每個(gè)實(shí)體這會(huì)生成兩個(gè)Swift文件粟矿,你的每個(gè)實(shí)體在這里都變成了 NSManagedObject的子類凰棉,這也是在代碼中我們使用的類。

托管對(duì)象

在AppDelegate里陌粹,Xcode會(huì)幫你做一些事情:

  • 首先它幫你獲取了持久化儲(chǔ)存的目錄撒犀,這也是App一般存數(shù)據(jù)的地方:
lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "edu.bupt.exialym.CoreDataTest" in the application's documents Application Support directory.
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
    }()
  • 接著將你的模型轉(zhuǎn)換為NSManagedObject類,這里獲取的CoreDataText.momd文件非常重要掏秩,它與你的工程名相對(duì)應(yīng):
lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = NSBundle.mainBundle().URLForResource("CoreDataTest", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()

持久化儲(chǔ)存協(xié)調(diào)器

持久化儲(chǔ)存器是程序訪問(wèn)持久化儲(chǔ)存的橋梁或舞。
在AppDelegate中,這個(gè)變量Xcode也創(chuàng)建好了:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason

            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()

在這里蒙幻,定義了與此持久化儲(chǔ)存協(xié)調(diào)器對(duì)應(yīng)的托管對(duì)象模型映凳、持久化儲(chǔ)存文件。

托管對(duì)象上下文

在AppDelegate中邮破,Xcode還定義了托管上下文诈豌,并指向了上面的持久化儲(chǔ)存協(xié)調(diào)器:

lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

當(dāng)托管對(duì)象改變時(shí),需要儲(chǔ)存當(dāng)前的托管對(duì)象上下文抒和,這時(shí)你所做的修改才能保存起來(lái)矫渔,這樣也為撤銷和重做提供了支持。增刪改查摧莽,只有查不需要保存庙洼。這個(gè)方法Xcode也在AppDelegate里生成了:

func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }

增刪改很大程度上是在查的基礎(chǔ)上完成的

//首先,規(guī)定獲取數(shù)據(jù)的實(shí)體
let request = NSFetchRequest(entityName: "Book")
//配置查詢條件镊辕,如果有需要還可以配置結(jié)果排序
let predicate = NSPredicate(format: "%K == %@", "name", nameText.text!)
request.predicate = predicate
var result:[NSManagedObject] = []
do{
    //進(jìn)行查詢油够,結(jié)果是一個(gè)托管對(duì)象數(shù)組
    result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
} catch {}
resultText.text = ""
for item in result {
    //用鍵值對(duì)的方式獲取各個(gè)值
    resultText.text! += "書名:\(item.valueForKey("name") as! String)  作者:\(item.valueForKey("author") as! String)\n"
}

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//向指定實(shí)體中插入托管對(duì)象
let object:Book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: appDelegate.managedObjectContext) as! Book
object.name = nameText.text
object.author = authorText.text
appDelegate.saveContext()

let request = NSFetchRequest(entityName: "Book")
if nameText.text != "" && authorText.text != "" {
    let predicate = NSPredicate(format: "%K == %@","name", nameText.text!)
    request.predicate = predicate
    var result:[NSManagedObject] = []
    do{
        result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
    } catch {}
    if result.count != 0{
        resultText.text = ""
        for item in result {
            //獲取到想要的對(duì)象,改想改的值
            item.setValue(authorText.text, forKey: "author")
            resultText.text! += "書名:\(item.valueForKey("name") as! String)  作者:\(item.valueForKey("author") as! String)\n"
        }
    }
}
appDelegate.saveContext()

let request = NSFetchRequest(entityName: "Book")
if nameText.text != "" && authorText.text != "" {
    let predicate = NSPredicate(format: "%K == %@","name", nameText.text!)
    request.predicate = predicate
    var result:[NSManagedObject] = []
    do{
        result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
    } catch {}
    if result.count != 0{
        for item in result {
            appDelegate.managedObjectContext.deleteObject(item)
        }
    }
}
appDelegate.saveContext()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末丑蛤,一起剝皮案震驚了整個(gè)濱河市叠聋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌受裹,老刑警劉巖碌补,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異棉饶,居然都是意外死亡厦章,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門照藻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)袜啃,“玉大人,你說(shuō)我怎么就攤上這事幸缕∪悍ⅲ” “怎么了晰韵?”我有些...
    開(kāi)封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)熟妓。 經(jīng)常有香客問(wèn)我雪猪,道長(zhǎng),這世上最難降的妖魔是什么起愈? 我笑而不...
    開(kāi)封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任只恨,我火速辦了婚禮,結(jié)果婚禮上抬虽,老公的妹妹穿的比我還像新娘官觅。我一直安慰自己,他們只是感情好阐污,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布休涤。 她就那樣靜靜地躺著,像睡著了一般疤剑。 火紅的嫁衣襯著肌膚如雪滑绒。 梳的紋絲不亂的頭發(fā)上闷堡,一...
    開(kāi)封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天隘膘,我揣著相機(jī)與錄音,去河邊找鬼杠览。 笑死弯菊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的踱阿。 我是一名探鬼主播管钳,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼软舌!你這毒婦竟也來(lái)了才漆?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤佛点,失蹤者是張志新(化名)和其女友劉穎醇滥,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體超营,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡鸳玩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了演闭。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片不跟。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖米碰,靈堂內(nèi)的尸體忽然破棺而出窝革,到底是詐尸還是另有隱情购城,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布虐译,位于F島的核電站工猜,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏菱蔬。R本人自食惡果不足惜篷帅,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拴泌。 院中可真熱鬧魏身,春花似錦、人聲如沸蚪腐。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)回季。三九已至家制,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間泡一,已是汗流浹背颤殴。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鼻忠,地道東北人涵但。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像帖蔓,于是被迫代替她去往敵國(guó)和親矮瘟。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容