折腾了一下午,跑通了 CoreData增加数据和查询
学习一门语言没那么简单~~~~好在iOS比较稳定
Git地址:
https://github.com/Wirhui/iOS-CoreDateDemo
注意
如果在简书中需要添加代码
按住Q按键上面的1的左边的波浪按键 在英文状态下 连按四下
分割线
import UIKit
import CoreData
class ViewController:UIViewController{
var stus :[StudentMO2] = [] ;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//找到上下文
let content = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//通过上下文找到这个库中的表
let entity =NSEntityDescription.entity(forEntityName:"Student", in: content)
//创建一个新的学生
let stu =NSManagedObject.init(entity: entity!, insertInto: content) as! StudentMO2
stu.name="wanghui"
stu.id=23
stu.score=99
//保存数据
do{
try content.save()
print("成功")
}catch {
print("失败")
}
//查询
let secReq =NSFetchRequest(entityName:"Student")
do{
try stus= content.fetch(secReq)as! [StudentMO2]
print("Hello!\(stus[0].name)")
}catch {
print("Hello!")
}
}
}
网友评论