swift 之本地?cái)?shù)據(jù)庫CoreData

Coredata 是對ios 中sqlite 的封裝,在xcode 中添加創(chuàng)建一個
<pre><code>
項(xiàng)目 -> new File -> Core Data -> Data Model -> 輸入名字-> 創(chuàng)建完畢
</code></pre>

創(chuàng)建.png

選擇.png

在項(xiàng)目中找到剛才創(chuàng)建的文件:

md截圖.png

如圖紅色的標(biāo)記:
步驟 1 : 添加一個 Entity 命名 為User
步驟 2 :向User Entity 實(shí)體類 添加屬性
步驟 3: 添加屬性類型

這些工作完成之后欲侮,便是將這樣entity 生成代碼

生成實(shí)體類.png

選擇model

選擇model.png

選擇實(shí)體佣蓉,點(diǎn)擊next生成在指定目錄下

選擇實(shí)體.png

最后涂身,在項(xiàng)目中使用coredata ,編寫兩個utils 類
CoreDataHelper 類<code><pre>
// CoreDataHelper.swift
// SwiftCoreDataSimpleDemo
//
// Created by CHENHAO on 14-6-7.
// Copyright (c) 2014 CHENHAO. All rights reserved.
//

import CoreData
import UIKit

class CoreDataHelper: NSObject{

let store: CoreDataStore!

override init(){
    // all CoreDataHelper share one CoreDataStore defined in AppDelegate
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    self.store = appDelegate.cdstore
    
    super.init()
    
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveContext:", name: NSManagedObjectContextDidSaveNotification, object: nil)
}

deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

// #pragma mark - Core Data stack

// Returns the managed object context for the application.
// Normally, you can use it to do anything.
// But for bulk data update, acording to Florian Kugler's blog about core data performance, [Concurrent Core Data Stacks – Performance Shootout](http://floriankugler.com/blog/2013/4/29/concurrent-core-data-stack-performance-shootout) and [Backstage with Nested Managed Object Contexts](http://floriankugler.com/blog/2013/5/11/backstage-with-nested-managed-object-contexts). We should better write data in background context. and read data from main queue context.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.

// main thread context

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.store.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
    }()

// Returns the background object context for the application.
// You can use it to process bulk data update in background.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.

lazy var backgroundContext: 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.store.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var backgroundContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
    backgroundContext.persistentStoreCoordinator = coordinator
    return backgroundContext
    }()


// save NSManagedObjectContext
func saveContext (context: NSManagedObjectContext) {
    var error: NSError? = nil
    if context.hasChanges && !context.save(&error) {
        // Replace this implementation 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 \(error), \(error!.userInfo)")
        abort()
    }
}

func saveContext () {
    self.saveContext( self.backgroundContext! )
}

// call back function by saveContext, support multi-thread
func contextDidSaveContext(notification: NSNotification) {
    let sender = notification.object as! NSManagedObjectContext
    if sender === self.managedObjectContext {
        NSLog("******** Saved main Context in this thread")
        self.backgroundContext!.performBlock {
            self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
        }
    } else if sender === self.backgroundContext {
        NSLog("******** Saved background Context in this thread")
        self.managedObjectContext!.performBlock {
            self.managedObjectContext!.mergeChangesFromContextDidSaveNotification(notification)
        }
    } else {
        NSLog("******** Saved Context in other thread")
        self.backgroundContext!.performBlock {
            self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
        }
        self.managedObjectContext!.performBlock {
            self.managedObjectContext!.mergeChangesFromContextDidSaveNotification(notification)
        }
    }
}

}
</code></pre>
CoreDataStore 類
<code><pre>
//
// CoreDataStore.swift
// SwiftCoreDataSimpleDemo
//
// Created by CHENHAO on 14-7-9.
// Copyright (c) 2014 CHENHAO. All rights reserved.
//

import Foundation
import CoreData

class CoreDataStore: NSObject{

let storeName = "anjibei"
let storeFilename = "anjibei.sqlite"

lazy var applicationDocumentsDirectory: NSURL = {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "me.iascchen.MyTTT" in the application's documents Application Support directory.
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1] as! NSURL
    }()

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(self.storeName, withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return 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
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.storeFilename)
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
        // 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 \(error), \(error!.userInfo)")
        abort()
    }
    
    return coordinator
    }()

}
</code></pre>
其中
let storeName = "anjibei"
let storeFilename = "anjibei.sqlite"
為你上述創(chuàng)建model 文件時(shí)候的名字老虫。

接下來呢允坚,就是需要在appdelagete 配置聲明
<pre><code>
lazy var cdstore: CoreDataStore = {
let cdstore = CoreDataStore()
return cdstore
}()

lazy var cdh: CoreDataHelper = {
    let cdh = CoreDataHelper()
    return cdh
    }()

</code></pre>


Paste_Image.png

配置完成漫试,可以使用了。
<pre><code>
func manageDB(){
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.cdh.managedObjectContext
    var row:User = NSEntityDescription.insertNewObjectForEntityForName("User",inManagedObjectContext:managedContext!) as! User
     row.username = "hello coredata"
     row.password = "wow"
    var error: NSError?
    if !managedContext!.save(&error) {
        println("Could not save \(error), \(error?.userInfo)")
    }
    //fetch families
    NSLog(" ======== Fetch ======== ")
    

    var fReq: NSFetchRequest = NSFetchRequest(entityName: "User")
    
    fReq.predicate = NSPredicate(format:"username CONTAINS 'h' ")
    
    var sorter: NSSortDescriptor = NSSortDescriptor(key: "username" , ascending: false)
    fReq.sortDescriptors = [sorter]
    
    fReq.returnsObjectsAsFaults = false
    
    var result = managedContext!.executeFetchRequest(fReq, error:&error)
    for resultItem in result! {
        var useritem = resultItem as! User
        PrintUtils.printLog("username",message: "Fetched Family for \(useritem.username) ")
    }
    
}

</code></pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末诡右,一起剝皮案震驚了整個濱河市安岂,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌稻爬,老刑警劉巖嗜闻,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蜕依,死亡現(xiàn)場離奇詭異桅锄,居然都是意外死亡琉雳,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進(jìn)店門友瘤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來翠肘,“玉大人,你說我怎么就攤上這事辫秧∈叮” “怎么了?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵盟戏,是天一觀的道長绪妹。 經(jīng)常有香客問我,道長柿究,這世上最難降的妖魔是什么邮旷? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮蝇摸,結(jié)果婚禮上婶肩,老公的妹妹穿的比我還像新娘。我一直安慰自己貌夕,他們只是感情好律歼,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著啡专,像睡著了一般险毁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上植旧,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天辱揭,我揣著相機(jī)與錄音,去河邊找鬼病附。 笑死问窃,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的完沪。 我是一名探鬼主播域庇,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼覆积!你這毒婦竟也來了听皿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤宽档,失蹤者是張志新(化名)和其女友劉穎尉姨,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體吗冤,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡又厉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年九府,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片覆致。...
    茶點(diǎn)故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡侄旬,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出煌妈,到底是詐尸還是另有隱情儡羔,我是刑警寧澤,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布璧诵,位于F島的核電站汰蜘,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏之宿。R本人自食惡果不足惜鉴扫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望澈缺。 院中可真熱鬧坪创,春花似錦、人聲如沸姐赡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽项滑。三九已至依沮,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間枪狂,已是汗流浹背危喉。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留州疾,地道東北人辜限。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像严蓖,于是被迫代替她去往敵國和親薄嫡。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評論 2 359

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