注释:本地数据库
func prepareCoreData() {
//1.获取momd文件的路径,类型必须是momd
let path = NSBundle.mainBundle().pathForResource("Person", ofType: "momd")
//2.获取被管理的对象模型
let model = NSManagedObjectModel(contentsOfURL: NSURL(fileURLWithPath: path!))
//3.创建存储器,主要是为了将CoreData数据库和模型关联起来
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model!)
//4.设置关联数据库的路径,NSHomeDirectory获取到的是沙盒目录的相对路径
let str = NSHomeDirectory() as NSString
let coreDataPath = str.stringByAppendingPathComponent("/ 0/Person.sqlite")
//5.关联数据库路径
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL(fileURLWithPath: coreDataPath), options: nil)
} catch let error {
print("关联错误:\(error)")
}
//6.创建上下文
context = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
//7.将存储器设置给上下文
context?.persistentStoreCoordinator = coordinator
/***********数据库环境搭建完毕************/
//读取数据库中已有的数据
//设置查询请求
let request = NSFetchRequest(entityName: "Student")
//开始查询。默认查询全部数据
do {
dataArray = try context?.executeFetchRequest(request) as! [Student]
self.tableView.reloadData()
} catch let error {
print("查询失败:\(error)")
}
}