Ripa Saha
Ripa Saha

Reputation: 2540

simple data insertion using realm swift

I'm an newbie in realm-swift. Trying to do an simple data insertion in realm DB. I'm getting following warning:-

WARNING: An RLMRealm instance was deallocated during a write transaction and
all pending changes have been rolled back. Make sure to retain a reference
to the RLMRealm for the duration of the write transaction. 

Here is my code :-

    //
//  Dog.swift
//  RealmDemo
//
//  Created by RIPA SAHA on 20/07/16.
//  Copyright © 2016 RIPA SAHA. All rights reserved.
//

import Foundation

class Dog {

    dynamic var name = ""

    dynamic var age = ""

}



//
//  ViewController.swift
//  RealmDemo
//
//  Created by RIPA SAHA on 19/07/16.
//  Copyright © 2016 RIPA SAHA. All rights reserved.
//

import UIKit
import RealmSwift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.



        let myDog = Dog()
        myDog.name = "puppies"
        myDog.age = "5"


        // Get the default Realm
        let realm = try! Realm()

        // Add to the Realm inside a transaction
        realm.beginWrite()


             realm.add(myDog)


        /*realm.add(myDog)
        realm.commitWrite()*/



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

any help would be appreciated...

Upvotes: 1

Views: 429

Answers (2)

Kerim Khasbulatov
Kerim Khasbulatov

Reputation: 722

Follow this example:

import Foundation
import RealmSwift

class Dog : Object {
  dynamic var name = ""
  dynamic var age = ""
}

Upvotes: 3

Luca Nicoletti
Luca Nicoletti

Reputation: 2427

Wrap your write code as follow:

try! realm.write {
   realm.add(myDog)
}

This should fix the problem

Upvotes: 1

Related Questions