如何为核心数据中的属性替换或设置新值?

How to replace or set a new value for an attribute in core data?

为了让事情更容易理解,我有一个应用程序,用户可以在其中输入他们选择的日期,可以是生日或特殊事件。从那里我将该日期存储在核心数据中并在我的 TableViewController 中获取结果。每次出现视图时,我都想从每个对象中检索日期并从所选日期中减去今天的日期以获得差异。然后 tableView 重新加载数据。当需要替换剩余天数并将其存储到数据库中时,我的问题就来了。我的问题出在这一行,我收到一条错误消息 "Type Int16 does not conform to protocol AnyObject"

//In my entity DaysLeft, I have the date the user chose stored as an attribute of type date as well as a theDaysLeft attribute of type Int16
        myList[index].setValue(daysLeft, forKey: "theDaysLeft")

这是我的完整代码:

var myList: Array<AnyObject> = []

override func viewWillAppear(animated: Bool) {

    let appDeleg: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let contexts: NSManagedObjectContext = appDeleg.managedObjectContext!
    let freq = NSFetchRequest(entityName: "DaysLeft")

    let sortDescriptor = NSSortDescriptor(key: "theDaysLeft", ascending: false)
    freq.sortDescriptors = [sortDescriptor]


    myList = contexts.executeFetchRequest(freq, error: nil)!


    //  Below automatically update the days left

    for var index = 0; index < myList.count; index++ {

        var data: NSManagedObject = myList[index] as NSManagedObject

        var chosenDate: NSDate = data.valueForKey("chosenDate") as NSDate
        var todayDate: NSDate = NSDate()

        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.DayCalendarUnit, fromDate: todayDate, toDate: chosenDate, options: nil)

        let secondsInADay = ((60 * 60) * 24)
        let daysLeft: Int16 = (components.hashValue / secondsInADay)

        //In my entity DaysLeft, I have the date the user chose stored as an attribute of type date as well as a theDaysLeft attribute of type Int16
        myList[index].setValue(daysLeft, forKey: "theDaysLeft")

    }

    tableView.reloadData()

如果您使用键值编码 (KVC),则必须使用对象。而不是 Int16 类型的变量,您必须创建一个 NSNumber,例如

myList[index].setValue(NSNumber(int16: daysLeft), forKey: "theDaysLeft")

如果从 myList 检索到的值是 NSManagedObject,这应该可以工作。

不过,您应该使用 NSManagedObject 子类。然后,您可以使用方便且经过验证的点表示法访问属性,并且可以使用像 Int16.

这样的原语