3

我的简单类 ClassWithOneArray 产生了这个错误:

Bitcast 要求两个操作数都是指针,或者两者都不是 %19 = bitcast i64 %18 to %objc_object*, !dbg !470 LLVM ERROR: Broken function found, 编译中止!命令 /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift 失败,退出代码为 1

但是,我的班级 ClassWithOneInt 没有。为什么?

class ClassWithOneInt {
    var myInt = Int()
    init(myInt: Int) {
        self.myInt = Int()
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myInt, forKey: "myInt")
    }
    init(coder aDecoder: NSCoder) {
        self.myInt = aDecoder.decodeObjectForKey("myInt") as Int
    }
}

class ClassWithOneArray {
    var myArray = String[]()
    init(myArray: String[]) {
        self.myArray = String[]()
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}
4

3 回答 3

3

正如我在评论中指出的那样,您的示例似乎在 beta 2 上编译得很好,尽管由于几个原因它仍然无法工作,因为encoderWithCoder有任何用途,ClassWithOneArray需要:

  1. 声明符合 NSCoding,
  2. 实施NSCoding,
  3. 从 NSObject 继承或实现 NSObjectProtocol,并且,
  4. 使用未损坏的名称。

总而言之,这意味着:

@objc(ClassWithOneArray)
class ClassWithOneArray:NSObject, NSCoding {
    var myArray: String[]
    init(myArray: String[]) {
        self.myArray = myArray
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}

此外,似乎在操场上没有简单的测试归档方法,可能是因为类没有正确注册。

let foo = ClassWithOneArray(myArray:["A"])

let data = NSKeyedArchiver.archivedDataWithRootObject(foo)

let unarchiver = NSKeyedUnarchiver(forReadingWithData:data)
unarchiver.setClass(ClassWithOneArray.self, forClassName: "ClassWithOneArray")
let bar = unarchiver.decodeObjectForKey("root") as ClassWithOneArray
于 2014-06-25T05:44:19.080 回答
0

看起来你的语法对于你想要完成的事情有点偏离 - 这样的事情应该可以工作:

class ClassWithOneInt {
    var myInt: Int
    init(myInt: Int) {
        self.myInt = myInt
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myInt, forKey: "myInt")
    }
    init(coder aDecoder: NSCoder) {
        self.myInt = aDecoder.decodeObjectForKey("myInt") as Int
    }
}

class ClassWithOneArray {
    var myArray: String[]
    init(myArray: String[]) {
        self.myArray = myArray
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}
于 2014-06-25T01:32:38.980 回答
0

根据我的经验,只需向您的班级声明协议“NSCoding”就可以解决问题。希望这可以帮助某人。

于 2014-08-01T23:56:27.313 回答