如何从 NSObject class 访问变量?

How to access variable from NSObject class?

我正在尝试学习 swift 中的 mvc 设计模式。所以我制作了名为 User 的模型 class,如下所示:

class User: NSObject {

var email : String!
var password : String!
var profilePictureUrl : String!

init(email: String, password: String, profilePictureUrl: String) {
    super.init()

    self.email = email
    self.password = password
    self.profilePictureUrl = profilePictureUrl
}}

我正在使用另一个 class 来存储名为 loginConnection:

的函数
class loginConnection: NSObject {

class func loginUserWithEmailPassword(email: String,password: String) -> User{

    return User(email: email, password: password, profilePictureUrl: "nil")

}}

我尝试从我的 loginViewController 设置和获取电子邮件、密码和 profilePictureUrl,但是当我打印 User 对象时我总是得到 nil。

var userObj : User!

@IBAction func loginAction(sender: UIButton) {

    if userEmailTextField.text?.isEmpty != nil && userPasswordTextField.text?.isEmpty != nil{

        loginConnection.loginUserWithEmailPassword(userEmailTextField.text!, password:userPasswordTextField.text!)

    }
}

@IBAction func registerAction(sender: UIButton) {

    print("\(userObj.email) >>>>> \(userObj.password)")

}

如何从用户 class 访问变量?

那么您必须执行以下操作:-

var userObj : User = User()

userObj = loginConnection.loginUserWithEmailPassword(userEmailTextField.text!, password:userPasswordTextField.text!)

之后

userObj.email

您是从 loginAction 调用 userObj 吗? 喜欢下面..

var userObj : User!

@IBAction func loginAction(sender: UIButton) {

if userEmailTextField.text?.isEmpty != nil && userPasswordTextField.text?.isEmpty != nil{

    userObj = loginConnection.loginUserWithEmailPassword(userEmailTextField.text!, password:userPasswordTextField.text!)

    print("\(userObj.email) >>>>> \(userObj.password)")
   }
}

loginUserWithEmailPassword return 用户 class 对象,因此您可以使用它来访问用户 class 属性

改变你的loginAction方法如下,

@IBAction func loginAction(sender: UIButton) {

if userEmailTextField.text?.isEmpty == false && userPasswordTextField.text?.isEmpty == false {

    self.userObj = loginConnection.loginUserWithEmailPassword(userEmailTextField.text!, password:userPasswordTextField.text!)

    print("\(userObj.email) >>>>> \(userObj.password)")
   }
}

1) 您正在将 userEmailTextField.text?.isEmptynilisEmpty returns Bool 值进行比较。

2) 您没有分配函数 loginUserWithEmailPassword.

返回的类型 User 的值

我不明白为什么这需要是一个 NSObject。通过使它成为一个结构,你可以删除 init 因为它会自动出现。同时删除!在大多数情况下,因为除非您知道自己在做什么,否则使用隐式展开的可选值是非常危险的。 Xcode 也将帮助自动完成,并就如何修复给出很好的建议。如果你这样做,你会发现编译器会在 运行 时间错误发生之前告诉你这些问题。

您声明了 User 的 userObj 实例,但您没有通过 loginUserWithEmailPassword 函数中的值将 return 分配给它。

在您的 viewController loginAction 中为您指定 userObj。

@IBAction func loginAction(sender: UIButton) {

        userObj = loginConnection.loginUserWithEmailPassword("Karan", password:"karanPassword")
        self.registerAction()
    }  

现在您将获得指定的用户名和密码。

@IBAction func registerAction(sender: UIButton) {

        print("\(userObj.email) >>>>> \(userObj.password)")

    }  

这里我在输出中得到了用户名和密码window