標籤:
SWIFT中使用CoreData來儲存本機資料,在建立項目的時候把 "Use Core Data"選項選上
項目建立完成後點擊尾碼為 .xcdatamodeld的那個檔案,點擊右下角"Add Entity"添加一個Entity後可以修改其名稱,接著在"Attributes"下面點擊“+”號添加一個
Attribute
接著就可以上代碼操作了,首先先添加引用
import CoreData
//It‘s necessary to code these two rows if you want to use CoreData
var applicationDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = applicationDelegate.managedObjectContext
//Get the entity by entityName
var entity = NSEntityDescription.entityForName("Notes", inManagedObjectContext: managedObjectContext!)
//Get the ManagedObject
var title = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)
//Set the ManagedObject Value for key
title.setValue(text, forKey: "title")
var error: NSError?
//Save content
if(managedObjectContext?.save(&error) == nil){
}
//Get data from the CoreData
var applicationDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = applicationDelegate.managedObjectContext
var fetchRequest = NSFetchRequest(entityName: "Notes")
var error:NSError?
var fetchResults = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
if let results = fetchResults{
var notes = results
}else{
println(error)
}
SWIFT 之CoreData初試