Yash R
Yash R

Reputation: 247

Unable to insert second record in realm database

I am using realm as my backend. I am storing two strings.The problem is when I insert the records first time it works perfectly but when I insert the records again it shows an error.

My code:

class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var tablee:UITableView!
@IBOutlet weak var msgTxt:UITextView!
@IBOutlet weak var img:UIImageView!
@IBOutlet weak var vieww:UIView!


let msg = Msg()
let realm = try! Realm()
lazy var msgs: Results<Msg> = { self.realm.objects(Msg.self) }()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
     print(Realm.Configuration.defaultConfiguration.fileURL!)
}
@IBAction func msgSend(_ sendeR:UIButton) {
    if img.image != nil {
        let image : UIImage = self.img.image!
        let imageData:NSData = UIImagePNGRepresentation(image)! as NSData
        let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
        print(strBase64)
        let pureStr = String(strBase64)
        msg.imgurl = pureStr!
    } else {
        msg.imgurl = "none"
    }
    msg.content = msgTxt.text
    let realm = try! Realm()
    do {
        try realm.write() {
            realm.add(msg)
        }
    } catch {

    }
    self.tablee.reloadData()
    self.msgTxt.text = ""
}
}

Error:

Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

Upvotes: 1

Views: 333

Answers (1)

Sweeper
Sweeper

Reputation: 270980

The error occurs because you only have one single Msg object created. Here:

let msg = Msg()

Since this is placed outside of a class, it will only create one instance of Msg every time the enclosing class is instantiated.

When you first press the button, everything is good. msg is saved into the database. When you press the button a second time, you are modifying the same msg object, which is already in the database! To modify something that's already saved, you need to put the code in a write block. But you didn't, so the exception occurs.

What I think you intended to do was to create a new Msg object every time the button is pressed. To do this, you need to declare msg as a local variable, or reassign msg in the IBAction.

@IBAction func msgSend(_ sendeR:UIButton) {
    msg = Msg() // this line creates a new Msg object so as not to modify the same one over and over.
    if img.image != nil {
        let image : UIImage = self.img.image!
        let imageData:NSData = UIImagePNGRepresentation(image)! as NSData
        let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
        print(strBase64)
        let pureStr = String(strBase64)
        msg.imgurl = pureStr!

Upvotes: 3

Related Questions