swift valueForKeyPath不起作用

时间:2015-09-30 10:56:28

标签: ios iphone xcode swift properties

我有功能

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(field!)上,应用程序崩溃并显示错误:

 *** 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值

2 个答案:

答案 0 :(得分:4)

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

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

var adID: NSNumber!

答案 1 :(得分:2)

您无法将valueForKeyPathOptionals一起使用。由于您将idTest声明为可选,因此您将遇到此崩溃。尝试下面的代码,它应该工作!

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

let testObj1 = STest()
testObj1.idTest = 1
testObj1.strTest = "test"
let objValue = testObj1.valueForKeyPath("idTest") as! Int