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.
解决方法: