上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc(Info),不然后面会报错,我也不知道为什么。
然后在viewController中添加代码如下代码来实现:
import UIKit import CoreData class ViewController: UIViewController { var tempInfo: Info! override func viewDidLoad() { super.viewDidLoad() if let managementContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext{ tempInfo = NSEntityDescription.insertNewObjectForEntityForName("Info", inManagedObjectContext: managementContext) as Info //相当于取到了Info,可以进行赋值操作 tempInfo.name = "cg" tempInfo.location = "xidian" //记得save var e: NSError? if managementContext.save(&e) != true { println("insert error \(e!.localizedDescription)") } if let managementContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext{ var fetchRequest = NSFetchRequest(entityName: "Info") var result = managementContext.executeFetchRequest(fetchRequest, error: &e) as [Info] if e != nil { println("fetch result error: \(e!.localizedDescription)") } else { for item: AnyObject in result { let temp = item as Info println("name: \(temp.name), localtion: \(temp.location)") } } } } } }以上代码的作用是通过代理的方式,先向Info中插入一个实例的值,name属性为cg,location属性为xidian,然后再进行查询,把打印出来,运行后中控台显示如下:
有了插入和查询,下面实现更新操作,在上面的代码中增加如下代码:
if let managementContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext { var fetchRequest = NSFetchRequest(entityName: "Info") fetchRequest.predicate = NSPredicate(format: "name = 'cg'", argumentArray: nil) var result = managementContext.executeFetchRequest(fetchRequest, error: &e) as [Info] if e != nil { println("fetch result error: \(e!.localizedDescription)") } else { for item: AnyObject in result { let temp = item as Info temp.name = "cggggg" println("name: \(temp.name), localtion: \(temp.location)") } managementContext.save(&e) } }
以上代码的作用是把name为cg的实例的name改成cggggg,运行结果如下:
现在来实现删除的操作,与update的操作类似,在update代码的基础上把修改名字的代码改成:
managementContext.deleteObject(temp)
就好了,现在我们试着删除名为cggggg的记录,可以看到cggggg已经不在了,在这就不截图了大家自己试试。