0
1

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.

[Swift]Realm Swift #2 - サンプル

Last updated at Posted at 2020-04-26

iOS でRealm Swift を 利用し、サンプルを作成してみました。

目次

・Realm Swift #1 クラス
・ Realm Swift #2 サンプル
・ Realm Swift #3 トラブル対応

サンプル

※ Source: RealmStudentAccess.swift

##Ream 定義

Student.swift
import RealmSwift
class Student: Object, Codable, NSCopying {
    @objc dynamic var studentId = ""
    @objc dynamic var name = ""
    @objc dynamic var age = 0
    
    override static func primaryKey() -> String? {
        return "studentId"
    }

[JSON]

{
"name": "jane",
"age": 12,
"studentId": "1"
}

##レコードの追加

RealmStudentAccess.swift
 //guard let data = dataStudentStr.data(using: .utf8) else {...}
 let obj = try JSONDecoder().decode(Student.self, from: data)
 try manager.add(obj: obj)

[結果ログ]
スクリーンショット 2020-04-26 22.23.38.png

##レコードの更新

RealmStudentAccess.swift
try manager.update(obj: student) {
     student.name = "test"
     student.age = 20
     print("2.update => findFirst updateStudent:" + student.description  )
}

[結果ログ]
スクリーンショット 2020-04-26 22.17.05.png

##レコードの削除

RealmStudentAccess.swift
//guard let primaryKey = manager.getPrimaryKey() else {...}
try manager.deleteWithQuery(query: "\(primaryKey) == '2' ")

[結果ログ]
スクリーンショット 2020-04-26 22.17.31.png

##レコード検索

let student =  manager.findByPrimaryKey(key: "1") 

[結果ログ]
スクリーンショット 2020-04-26 22.17.21.png

index

≪ Realm Swift #1 クラス  ーーー  Realm Swift #3 トラブル対応 ≫       

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?