错误“表达式类型'@lvalue字符串”是什么?没有更多上下文就意味着模棱两可”是什么意思?

时间:2019-06-25 11:01:12

标签: swift xcode realm

enter image description here

在TableView Controller中,我有多个UITextField,它们允许用户输入一些信息并使用Realm保存来自用户输入的数据。

我使用以下方式添加数据,但出现错误消息:“表达式类型'@lvalue字符串?”没有更多上下文就变得模棱两可”

import UIKit
import RealmSwift

class NewIdeaCreation: UITableViewController, UITextFieldDelegate {

   let realm = try! Realm()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}    

@IBAction func createButtonPressed(_ sender: UIButton) {

    try realm.write {
        realm.add(nameTextField.text) //Error here
    }
    self.dismiss(animated: true, completion: nil)
}


@IBOutlet weak var nameTextField: UITextField!

}

我在这里应该做什么?

2 个答案:

答案 0 :(得分:2)

  • 首先添加对象模型
class Item: Object {

    @objc dynamic var itemId: String = UUID().uuidString
    @objc dynamic var body: String = ""
    @objc dynamic var isDone: Bool = false
    @objc dynamic var timestamp: Date = Date()

    override static func primaryKey() -> String? {

        return "itemId"

    }


}
  • 更新您的代码
 @IBAction func createButtonPressed(_ sender: UIButton) {

        try realm.write {
            realm.add(nameTextField.text) //Error here
        }

        self.dismiss(animated: true, completion: nil)

    }
  • 为此
 @IBAction func createButtonPressed(_ sender: UIButton) {

        let item = Item()
        item.body = nameTextField.text ?? ""
        try! self.realm.write {
        self.realm.add(item)
       }

        self.dismiss(animated: true, completion: nil)

    }

答案 1 :(得分:1)

您只能将Realm Object保存到领域数据库中。 String不是Realm Object

您可以创建一个具有String的对象:

class StringObject: Object {
    @objc dynamic var string = ""
    // Your model probably have more properties. If so, add them here as well
    // If not, that's ok as well
}

现在,您可以改为保存StringObject

do {
    try realm.write {
        let stringObject = StringObject()
        stringObject.string = nameTextField.text ?? ""
        realm.add(stringObject)
    }
} catch let error {
    print(error)
}