问题
In a TableView Controller, I have multiple UITextFields that allow users to input some information and use Realm to save data from users' input.
I use the following ways to add the data but I got the error saying "Expression type '@lvalue String?' is ambiguous without more context"
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!
}
What should I do here?
回答1:
You can only save Realm Object
s into a realm database. String
is not an Realm Object
.
You can create an object that has a String
though:
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
}
Now you can save a StringObject
instead:
do {
try realm.write {
let stringObject = StringObject()
stringObject.string = nameTextField.text ?? ""
realm.add(stringObject)
}
} catch let error {
print(error)
}
回答2:
- First Add Object Model
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"
}
}
- Update Your Code
@IBAction func createButtonPressed(_ sender: UIButton) {
try realm.write {
realm.add(nameTextField.text) //Error here
}
self.dismiss(animated: true, completion: nil)
}
- To This
@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)
}
来源:https://stackoverflow.com/questions/56752579/what-does-error-expression-type-lvalue-string-is-ambiguous-without-more-con