CoreData练习

首先到CoreData项目的xcdatamodled中,添加ENTITYS实例
练习添加了:ENTITYS Person,attribute name:String

var people = [NSManagedObjectContext]()

1> 保存 (五步)

1、获取总代理(appDelegate)和托管对象总管(managedObjectContext )

    let appDelegate = UIApplication.shareApplication().delegate as AppDelegate
    let managedObjectContext = appDelegate.manegedObjectContext!

2、建立一个entity

    let entity = NSEntityDescription.entityForName("Person", inManaedObjectContext: managedObjectContext )
    let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext )

3、保存数据到NSManagedObject实例(person)

    person.setValue(names, forKey: "name")    

4、保存entity到托管对象内容总管中(managedObjectContext )

   managedObjectContext.save() {

5、保存数据到数组中,更新UI

    people.apend(person)

例子函数:

func saveCoreDate(text: String) {
        // 1 
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedObjectContext = appDelegate.managedObjectContext

        // 2 
        let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContext)
        let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)

        // 3
        person.setValue(text, forKey: "name")

        // 4
        //var error: NSError?
        do {
            try managedObjectContext.save()
        } catch let error {
            print("managedObjectContext can't save!, Error: \(error)")
        }

        // 5
        people.append(person)
    }

2> 获取 (四步)

1、获取总代理(appDelegate)和托管对象总管(managedObjectContext )

    let appDelegate = UIApplication.shareApplication().delegate as AppDelegate
    let managedObjectContext = appDelegate.manegedObjectContext!

2、建立一个获取数据请求

    let fetchRequest = NSFetchRequest(entityName: "Person")

3、执行请求,获取数据

    let fetchedRequest = managedObjectContext.executeFetchRequest(fetchRequest, error: )

4、保存到people,刷新列表

    people = fetchedRequest    

例子函数:

    func fetchCoreData() {
        // 1
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedObjectContext = appDelegate.managedObjectContext

        // 2
        let fetchRequest = NSFetchRequest(entityName: "Person")

        // 3
        do {
            let fetchedRequest = try managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]

        // 4
            people = fetchedRequest
            // 刷新列表
            self.tableView.reloadData()
        } catch let error {
            print("Can't fetch Person CoreData. Error: \(error).")
        }
    }

你可能感兴趣的:(CoreData练习)