【问题标题】:Objects in Swift: Value of 'Object' has no memberSwift 中的对象:“对象”的值没有成员
【发布时间】:2016-02-12 01:13:40
【问题描述】:

这是我的笨蛋。

我在一个名为 functions.swift 的文件中拥有这个可爱的小函数

//functions.swift

     func latestActiveGoal() -> Object {
            let realm = try! Realm()
            let currentGoal = realm.objects(Goal).filter("Active == 1").sorted("CreatedOn").last
            return currentGoal!
        }

它返回一个Goal 对象。 (一个目标可能是想减肥,或者停止对 Swift 如此无能)。

在不同的视图控制器中,我想访问这个对象。这是我正在尝试的:

//viewController.swift

@IBOutlet weak var aimText: UILabel!

let funky = functions()

    func getGoals(){

            var currentGoal = funky.latestActiveGoal()
            print(currentGoal)

            aimText.text = currentGoal.Title
    }

print(CurrentGoal) 输出显示如下:

Goal {
    id = 276;
    Title = Goal Title;
    Aim = Aim;
    Action = Nothing;
    Active = 1;
    CreatedOn = 2016-02-12 00:14:45 +0000;
}

aimText.text = currentGoal.TitleaimText = currentGoal.Title 都抛出错误:

Value of 'Object' has no member 'Title'

通过打印对象的内容,我可以看到数据,但不知道如何。非常感谢任何帮助。

【问题讨论】:

  • 请显示完整的错误信息。
  • @BryanChen 按照建议用错误消息更新了我的问题

标签: swift swift2 realm


【解决方案1】:

正如错误消息所说,currentGoalObject 类型的值,它没有成员 Title

这是因为函数 latestActiveGoal 返回 Object 而不是 Goal。您只需要通过更改返回类型使其返回Goal

func latestActiveGoal() -> Goal {

【讨论】:

    【解决方案2】:

    只需将您的函数替换为以下代码即可。 它将完美运行。

    这个函数会检查目标是否可用,然后只有它会返回。

    func latestActiveGoal() -> Object? {
                let realm = try! Realm()
                let currentGoals = realm.objects(Goal).filter("Active == 1").sorted("CreatedOn")
                if currentGoals.count > 0 {
                     return currentGoals.last;
                }
                return nil;
            }
    

    您的getGoals 方法如下。

    func getGoals(){    
        if let currentGoalObject = funky.latestActiveGoal() {
            print(currentGoalObject)
            let goal = currentGoalObject as! Goal
            print(goal.Title)
            aimText.text = goal.Title
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2017-12-21
      • 2020-02-03
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多