CoreData 是 一個可以用來管理對象生命周期、對象層級、數據持久化存儲的蘋果官方框架。
下面來看看如何用swift語言來使用CoreData呢?
1 打開Xcode,選擇Xcode project
2 選擇開發平臺及模板應用,這里選擇ios single view Application
3 為項目命名,注意:需要勾選Use Core Data
4 當項目創建好后(如下圖),打開左側的.xcdatamodeld 文件,在這里創建實體
5創建的實體(表單),刪除操作,選中--->直接按 刪除鍵(delete) 就可以刪除不想要的表單!
6為實體創建一個NSManagerObject 子類,右鍵點擊選擇New File,新建一個NSManagedObject subclass文件
7 完成后就會看到左側目錄下會自動多了兩個文件:PeoPle+CoreDataProperties.swift 和People.swift(其實有People.swift這一個文件就可以了)
PeoPle+CoreDataProperties.swift 文件代碼:
importFoundation
importCoreData
extensionPeople{
@NSManagedvarage:NSNumber?
@NSManagedvarid:NSNumber?
@NSManagedvarname:String?
}
People.swift 文件代碼:
importFoundation
importCoreData
@objc(People)//注意這行代碼是要自己添加的哈
classPeople:NSManagedObject{
// Insert code here to add functionality to your managed object subclass
}
8 接下來,我們就可以打開ViewController.swift 操作實體 ,采用CoreData 進行存儲了
importUIKit
importCoreData
//import CoreData
classViewController:UIViewController{
overridefuncviewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.saveCoreDate()//創建對象并保存數據
self.fetchCoreData()//查詢對象并進行修改和刪除操作
}
//添加數據
funcsaveCoreDate(){
//加載AppDelegate
letappDel =UIApplication.sharedApplication().delegateas!AppDelegate
//獲取管理的上下文
letcontext = appDel.managedObjectContext
//創建一個實例并給屬性賦值
letpeople =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{
trycontext.save()
print("保存成功")
}catchleterror{
print("context can't save!, Error:\(error)")
}
}
funcfetchCoreData (){
//加載AppDelegate
letappDel =UIApplication.sharedApplication().delegateas!AppDelegate
//獲取管理的上下文
letcontext = appDel.managedObjectContext
//聲明數據請求實體
letfetchRequest =NSFetchRequest(entityName:"People")
//? ? ? ? let predicate = NSPredicate(format:"id=1")? //設置查詢條件按照id查找不設置查詢條件,則默認全部查找
//? ? ? ? fetchRequest.predicate=predicate
//執行查詢操作
do{
letpeopleList =
trycontext.executeFetchRequest(fetchRequest)as! [NSManagedObject]
print("打印查詢結果")
forpersoninpeopleListas! [People] {
print("查詢到的人是\(person.name!)")
//修改操作:將查詢到的結果修改后,再調用context.save()保存即可
if(person.name=="小紅"){
person.name="小花"
}
//刪除操作:將查詢到的額結果刪除后,再調用context.save()保存即可
if(person.name=="小明"){
context.deleteObject(person)
}
}
}catchleterror{
print("context can't fetch!, Error:\(error)")
}
do{
trycontext.save()
print("保存成功")
}catchleterror{
print("context can't save!, Error:\(error)")
}
}
overridefuncdidReceiveMemoryWarning() {
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.
解決方法: