ios - 无法访问类对象变量

标签 ios swift class oop variables

我正在使用 Swift 2 创建一个函数,该函数从我编写的类中创建一堆对象。

现在,问题是,当我添加一个新对象时,我没有问题,我从该函数和它存储数据的 init() 函数中多次检查。 (从 init() 函数打印 self.myVariable 是有效的)。

但是,当我稍后去检索我的变量时,例如

 if let dog: Animal? = Animal.init(id : "12345"){
print(dog?.legs)}

即使我 checkin 了 Animal 类并且它成功初始化了 Animal 对象“dog”,它也会打印 nil。

如果有人知道为什么会发生这种情况,那将非常有用且值得赞赏。

这是实际代码的链接,Animal 类只是一个示例,但这可能更有用:Class & Function

最佳答案

这是对您的类(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/

相关文章:

iphone - 阻止 iPhone 应用程序在 iPad 上运行

ios - UIPageViewController 实现 - 更改 View Controller 后黑屏

ios - UICollectionReusableView 标题不调整旋转大小 - 约束?

c++ - 类和结构嵌套

ios - 购买后更换背景图片

ios - 当状态更改时,如何防止 SceneKit 场景重新渲染不佳?

iOS/Swift - 无法在 Init() 上设置枚举值

java - 使用类声明用整数和字符串填充数组

Python 如何覆盖子类中的类成员并从父类访问它?

ios - 应用程序收到推送通知时的操作