我想获取核心数据属性的值,在获得此对象/值后,我想更新它。这是我的代码:
var numberOfChanges:Int32?
numberOfChanges = theme.valueForKey("numberThemeChanged") as Int32
var newValueThemeChanges:Int32?
newValueThemeChanges = numberOfChanges+1
theme.setValue(newValueThemeChanges, forKey: "numberThemeChanged")
我收到以下错误:
Type 'Int32' does not conform to protocol 'AnyObject'
:numberOfChanges = theme.valueForKey("numberThemeChanged") as Int32
。'Int32' is not identical to 'AnyObject'
:theme.setValue(newValueThemeChanges, forKey: "numberThemeChanged")
你知道我怎么做/我的代码有什么问题吗? 谢谢你的回答!
答案 0 :(得分:4)
键值编码方法
func valueForKey(key: String) -> AnyObject?
func setValue(value: AnyObject?, forKey key: String)
使用类型AnyObject
的值,对于整数属性
是NSNumber
的实例。
Int
和NSNumber
之间存在自动桥接,但没有
在Int32
和NSNumber
之间(这与此无关)
事实上,您在Core Data中将属性定义为“Integer 32”
模特督察)。
您有几种选择:
只需使用Int
类型的变量:
var numChanges = theme.valueForKey("numberThemeChanged") as Int
numChanges++
theme.setValue(numChanges, forKey: "numberThemeChanged")
使用Int32
并明确转换为NSNumber
:
var numberOfChanges = (theme.valueForKey("numberThemeChanged") as NSNumber).intValue // Int32
numberOfChanges++
theme.setValue(NSNumber(int: numberOfChanges), forKey: "numberThemeChanged")
使用Xcode - >编辑 - >创建NSManagedObject子类...并选中“使用基本数据类型的标量属性”选项。 这将为您提供具有属性
的托管对象子类@NSManaged var numberThemeChanged: Int32
并且您可以在没有键值编码的情况下访问该属性:
var numberOfChanges = theme.numberThemeChanged
numberOfChanges++
theme.numberThemeChanged = numberOfChanges
这是一个完整的“创建或更新”示例:
var theme : Entity!
let request = NSFetchRequest(entityName: "Entity")
var error : NSError?
if let result = context.executeFetchRequest(request, error: &error) as [Entity]? {
if result.count > 0 {
// (At least) one object found, set `theme` to the first one:
theme = result.first!
} else {
// No object found, create a new one:
theme = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context) as Entity
// Set an initial value:
theme.setValue(0, forKey: "numberThemeChanged")
}
} else {
println("Fetch failed: \(error?.localizedDescription)")
}
// Get value and update value:
var numChanges = theme.valueForKey("numberThemeChanged") as Int
numChanges++
theme.setValue(numChanges, forKey: "numberThemeChanged")
// Save context:
if !context.save(&error) {
println("Save failed: \(error?.localizedDescription)")
}
println(numChanges)