使用realm swift进行简单的数据插入

时间:2016-07-21 05:43:44

标签: ios swift realm

我是一个快速领域的新手。尝试在领域DB中进行简单的数据插入。 我收到了以下警告: -

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. 

这是我的代码: -

    //
//  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.
    }


}

任何帮助将不胜感激......

2 个答案:

答案 0 :(得分:3)

请遵循以下示例:

{{1}}

答案 1 :(得分:1)

将您的编写代码包装如下:

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

这应解决问题