我正在使用 Swift 2 创建一个函数,该函数从我编写的类中创建一堆对象。
现在,问题是,当我添加一个新对象时,我没有问题,我从该函数和它存储数据的 init() 函数中多次检查。 (从 init() 函数打印 self.myVariable 是有效的)。
但是,当我稍后去检索我的变量时,例如
if let dog: Animal? = Animal.init(id : "12345"){
print(dog?.legs)}
即使我 checkin 了 Animal 类并且它成功初始化了 Animal 对象“dog”,它也会打印 nil。
如果有人知道为什么会发生这种情况,那将非常有用且值得赞赏。
最佳答案
这是对您的类(class)代码here的回应.
在 init 函数内部,您永远不会设置类变量 id。您可以按如下方式设置:
query.getObjectInBackgroundWithId(id as String) { (object: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
}
else {
if let atm = object {
print("ATM found")
self.bank = atm["bank"] as? NSString
self.type = atm["type"] as? NSNumber
self.location = atm["location"] as? PFGeoPoint
self.description = atm["description"] as? NSString
// Set id to whatever you'd like here
self.id = atm.objectId!
}
}
}
关于ios - 无法访问类对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093431/