gpt4 book ai didi

ios - 快速 valueForKeyPath 不起作用

转载 作者:可可西里 更新时间:2023-11-01 00:23:34 25 4
gpt4 key购买 nike

我有功能

func findObjectInArray(array: [AnyObject], field: String?, fieldValue: AnyObject, startFromTheBeginning: Bool, minIndexTemp: Int, maxIndexTemp: Int) -> AnyObject?

我有:

var minIndex = minIndexTemp
var maxIndex = maxIndexTemp
if (array.count == 0 || minIndex < 0 || maxIndex < 0) {
return nil
}
if (minIndex > maxIndex) {
let rem = minIndex;
minIndex = maxIndex;
maxIndex = rem;
}
if (maxIndex >= array.count) {
maxIndex = array.count - 1;
}
let startIndex = startFromTheBeginning ? minIndex : maxIndex;
let endIndex = startFromTheBeginning ? maxIndex : minIndex;

for (var i = startIndex; (startFromTheBeginning ? i <= endIndex : i >= 0); (startFromTheBeginning ? i++ : i--)) {
let object = array[i]
var objectFieldValue: AnyObject? = nil
if (field != nil) {
print("test = ", (object as! SAd).adID)
objectFieldValue = object.valueForKeyPath(field!)
}

我在崩溃前记录了我看到 test = 1 。所以这意味着 object 被转换为 SAd 并且它有字段 adID,但是在 objectFieldValue = object.valueForKeyPath(字段!) 应用程序因错误而崩溃:

 *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Project.SAd 0x12d731930> valueForUndefinedKey:]: this class is not key value coding-compliant for the key adID

这是类

class SAd: NSObject {
var adID: Int!
var bloggerID: Int!
var createdOn: NSDate!
var duration: Int!
var fav: Int!
var price: Double!
var text: String!
var countries: [String]!
var categories: [String]!
var deleted: Bool!
}

实际上,您可以非常简单地在代码中测试相同的行为:

创建类:

class STest: NSObject {
var idTest: Int?
var strTest: String?
}

在你的 AppDelegate 文件中:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let testObj1 = STest()
testObj1.idTest = 1
testObj1.strTest = "test"
let objValue = testObj1 .valueForKeyPath("idTest")

return true
}

您将在 let objValue = testObj1 .valueForKeyPath("idTest") 行看到崩溃

但如果您将此行替换为 let objValue = testObj1 .valueForKeyPath("strTest") 它将起作用。所以问题出在Int值上

最佳答案

您不能将 KVC 与可选的 Swift 数字结构类型一起使用,例如 IntUIntFloatDoubleBool。简单地说,这些类型与 AnyObject 不兼容,无法桥接。

在您的示例中,您可以使用:

var adID: NSNumber!

关于ios - 快速 valueForKeyPath 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864333/

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