在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!
}
我在这里应该做什么?
答案 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)
}