gpt4 book ai didi

ios - 更新 Int32 类型的 CoreData 属性

转载 作者:可可西里 更新时间:2023-11-01 00:53:12 26 4
gpt4 key购买 nike

我想获取核心数据属性的值,在获取此对象/值后我想更新它。这是我的代码:

var numberOfChanges:Int32?
numberOfChanges = theme.valueForKey("numberThemeChanged") as Int32
var newValueThemeChanges:Int32?
newValueThemeChanges = numberOfChanges+1
theme.setValue(newValueThemeChanges, forKey: "numberThemeChanged")

我收到以下错误:

  1. Type 'Int32' does not conform to protocol 'AnyObject'在这行代码中:numberOfChanges = theme.valueForKey("numberThemeChanged") as Int32 .
  2. 'Int32' is not identical to 'AnyObject'在这行代码中:theme.setValue(newValueThemeChanges, forKey: "numberThemeChanged")

你知道我该怎么做/我的代码有什么问题吗?感谢您的回答!

最佳答案

键值编码方法

func valueForKey(key: String) -> AnyObject?
func setValue(value: AnyObject?, forKey key: String)

使用 AnyObject 类型的值,对于整数属性这些是 NSNumber 的实例。

IntNSNumber 之间有一个自动桥接,但不是Int32NSNumber 之间(这与事实上,您在核心数据中将属性定义为“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 -> Editor -> Create NSManagedObject subclass ... 并勾选“Use scalar properties for primitive data types”选项。这将为您提供一个具有属性的托管对象子类

    @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)

关于ios - 更新 Int32 类型的 CoreData 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29446126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com