swift:CoreData簡單入門(增加、查詢、修改、刪除)(詳細講解)
CoreData 是 一個可以用來管理 物件生命週期、物件層級、資料持久化儲存 的蘋果官方框架。
下面來看看如何用swift語言來使用CoreData呢?
1 開啟Xcode,選擇Xcode project
2 選擇開發平臺及模板應用,這裡選擇ios single view Application
3 為專案命名,注意:需要勾選Use Core Data
4 當專案建立好後(如下圖),開啟左側的.xcdatamodeld 檔案,在這裡建立實體
5 為實體建立屬性(People :id name age )(ps:本來是想寫person的,結果寫成了people,o(╯□╰)o。。。)
6 為實體建立一個NSManagerObject 子類,右鍵點選選擇New File,新建一個NSManagedObject subclass檔案
7 完成後就會看到左側目錄下會自動多了兩個檔案:PeoPle+CoreDataProperties.swift 和People.swift (其實有People.swift這一個檔案就可以了)
PeoPle+CoreDataProperties.swift 檔案程式碼:
import Foundation
import CoreData
extensionPeople {
@NSManaged var age: NSNumber
@NSManaged var id: NSNumber?
@NSManaged var name:String?
}
People.swift 檔案程式碼:import Foundation
import CoreData
@objc(People)//注意這行程式碼是要自己新增的哈
class People: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
8 接下來,我們就可以開啟ViewController.swift 操作實體 ,採用CoreData 進行儲存了import
import CoreData
//import CoreData
class ViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.saveCoreDate()//建立物件並儲存資料
self.fetchCoreData()//查詢物件並進行修改和刪除操作
}
//新增資料
func saveCoreDate(){
//載入AppDelegate
let appDel = UIApplication.sharedApplication().delegateas! AppDelegate
//獲取管理的上下文
let context = appDel.managedObjectContext
//建立一個例項並給屬性賦值
let people = NSEntityDescription.insertNewObjectForEntityForName("People", inManagedObjectContext: context)as! People
people.id =2
people.name ="小紅"
people.age =12
//下面這種賦值方式也可以的
// let entity = NSEntityDescription.entityForName("People", inManagedObjectContext: context)
// let people = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
// people.setValue(1, forKey: "id")
// people.setValue("小明", forKey: "name")
// people.setValue(10, forKey: "age")
//儲存資料
do {
try context.save()
print("儲存成功")
}catch let error{
print("context can't save!, Error:\(error)")
}
}
func fetchCoreData (){
//載入AppDelegate
let appDel = UIApplication.sharedApplication().delegateas! AppDelegate
//獲取管理的上下文
let context = appDel.managedObjectContext
// 宣告資料請求實體
let fetchRequest = NSFetchRequest(entityName: "People")
// let predicate = NSPredicate(format:"id=1") //設定查詢條件按照id查詢不設定查詢條件,則預設全部查詢
// fetchRequest.predicate=predicate
//執行查詢操作
do {
let peopleList =
try context.executeFetchRequest(fetchRequest)as! [NSManagedObject]
print("列印查詢結果")
for person in peopleListas! [People] {
print("查詢到的人是\(person.name!)")
//修改操作:將查詢到的結果修改後,再呼叫context.save()儲存即可
if (person.name =="小紅"){
person.name="小花"
}
//刪除操作:將查詢到的額結果刪除後,再呼叫context.save()儲存即可
if (person.name =="小明"){
context.deleteObject(person)
}
}
}catchlet error{
print("context can't fetch!, Error:\(error)")
}
do {
try context.save()
print("儲存成功")
}catch let error{
print("context can't save!, Error:\(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
9 執行結果如下:
注意:如果程式碼執行提示
2016-03-05 01:15:36.755 MyCoreData[1931:55760] CoreData: warning: Unable to load class named 'MyCoreData.People' for entity 'People'. Class not found, using default NSManagedObject instead. 解決方法:10 最後,我把整個工程提交到了github上面,有需要的可以下載看一下。