为了简单易懂,我有一个应用程序,其中用户输入他们选择的日期,可以是生日或特殊事件。从那里我将该日期存储在核心数据中并在我的TableViewController中获取结果。每次出现视图时,我都希望从每个对象中检索日期,并从所选日期中减去今天的日期以获得差异。然后tableView重新加载数据。当我需要更换剩余的时间并将其存储到数据库中时,我的问题就来了。我的问题是在这个特定的行,我得到一个错误说“类型Int16不符合协议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()
答案 0 :(得分:2)
如果使用键值编码(KVC),则必须使用对象。您需要创建Int16
,而不是类型为NSNumber
的变量,而不是
myList[index].setValue(NSNumber(int16: daysLeft), forKey: "theDaysLeft")
如果从myList
检索到的值为NSManagedObject
,应该有效。
但是,你应该使用NSManagedObject
子类。然后,您可以使用方便且经验证的点符号访问属性,并且可以使用Int16
之类的基元。