CoreData在更新后未保存信息

时间:2015-07-29 15:47:13

标签: ios swift core-data save edit

当按下addButton时,此函数应该将当前日期添加到存储在内存中的列表中,但是每当应用程序关闭并重新加载时,新日期都不会出现。切换视图后,数据似乎也消失了。

var selectedPersonFirst = ""
var selectedPersonLast = ""
let today = NSDate()



let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

@IBAction func addButtonPressed(sender: AnyObject) {

    let entityDescription = NSEntityDescription.entityForName("People", inManagedObjectContext: managedObjectContext!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    let firstPred = NSPredicate(format: "(firstName = %@)", selectedPersonFirst)
    let secondPred = NSPredicate(format: "(lastName = %@)", selectedPersonLast)

    let predicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [firstPred, secondPred])
    request.predicate = predicate

    var error: NSError?

    var objects = managedObjectContext?.executeFetchRequest(request, error: &error)

    if let results = objects{

        let days = results[0].valueForKey("days") as! NSMutableArray
        days.addObject(NSDate())

        let person = results[0] as! People
        person.setValue(days, forKey: "days")

    }

    managedObjectContext!.save(nil)

    self.tableView.reloadData()

}

这是NSManagedObject的人类子类:

import Foundation
import CoreData

class People: NSManagedObject {

    @NSManaged var days: AnyObject
    @NSManaged var dayZero: NSDate
    @NSManaged var firstName: String
    @NSManaged var gender: String
    @NSManaged var lastName: String

}

创建days NSMutableArray的ViewController:

import UIKit
import CoreData

class NewPersonViewController: UIViewController {

    @IBOutlet weak var firstName: UITextField!
    @IBOutlet weak var lastName: UITextField!
    @IBOutlet weak var gender: UISegmentedControl!
    @IBOutlet weak var dayZeroDate: UIDatePicker!

    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    var personName : String = ""
    var currentDayNumber : Int? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        if segue.identifier == "DoneNewPersonSegue" {

            let entityDescription = NSEntityDescription.entityForName("People", inManagedObjectContext: managedObjectContext!)

            let person = People(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)

            person.firstName = self.firstName.text
            person.lastName = self.lastName.text
            person.days = NSMutableArray()
            person.gender = gender.description
            person.dayZero = dayZeroDate.date

            save()

        }



    }

    func save() {
        var error : NSError?
        if(managedObjectContext!.save(&error) ) {
            println(error?.localizedDescription)
        }
    }


}

数据模型:

Data Model

1 个答案:

答案 0 :(得分:0)

问题在于我使用的是可变类型,因此更改并未调用setter方法。我更改了代码以创建对象的副本,以便识别更改:

let days1 = results[0].valueForKey("days") as! NSMutableArray
let days = days1.mutableCopy() as! NSMutableArray 

days.addObject(NSDate())
let person = results[0] as! People

person.setValue(days, forKey: "days”)