1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RealmSwift いつでも使える様に書き残し(保存、取得、削除)

Posted at

#今回の内容

  • Realmにデータを保存、取得、削除する関数を簡単に書き残しておきます。

#コード

##Model

import RealmSwift

class RealmDatasModel:Object{
    
    @objc dynamic var realmDataOne = String()
    @objc dynamic var realmDataTwo = String()
    
}

##class作成

import RealmSwift

class RealmCRUDModel{
    
    var readResultRealmDataArray:[[String:String]] = []   
}

##保存

extension RealmCRUDModel{
    
    func createRealmData(createContentOne:String,createContentTwo:String){
        
        do{
            let realm = try Realm()
            let realmDatasModel = RealmDatasModel()

            realmDatasModel.realmDataOne = createContentOne
            realmDatasModel.realmDataTwo = createContentTwo
            
            try realm.write({
                
                realm.add(realmDatasModel)
            })
            
            print("createRealmData\(realm.objects(RealmDatasModel.self))")
        }catch{
            
            //エラー処理
        }
        
    }
}

##取得

extension RealmCRUDModel{
    
    func readRealmData(){
        
        do{
            
            let realm = try Realm()
            
            readResultRealmDataArray = []
            
            realm.objects(RealmDatasModel.self).forEach { realmData in
                
                readResultRealmDataArray.append(["realmDataOne":realmData.realmDataOne,
                                                 "realmDataTwo":realmData.realmDataTwo])

                print("readRealmData\(readResultRealmDataArray)")
            }
        }catch{
            
            //エラー処理
        }
    }
    
}

##削除

extension RealmCRUDModel{
    
    func deleteRealmData(){
        
        do{
           
            let realm = try Realm()
            
            try realm.write({
                
                realm.delete(realm.objects(RealmDatasModel.self))
            })
            
        }catch{
            
            //エラー処理
        }
    }
}

#終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?