1.임포트
import RealmSwift
2.스키마 정의(테이블 생성)
// LocalOnlyQsTask is the Task model for this QuickStart
class LocalOnlyQsTask: Object {
@Persisted var name: String = ""
@Persisted var owner: String?
@Persisted var status: String = ""
//초기화
convenience init(name: String) {
self.init()
self.name = name
}
}
-한번 빌드된 앱에서 위 스키마의 내용이 바뀌게 되면 마이그레이션이 필요하다
-앱 삭제 후 다시 빌드
3.위치 가져오기
// Open the local-only default realm
let localRealm = try! Realm()
4.CRUD(Create(생성), Read(읽기), Update(갱신), Delete(삭제))
// Add some tasks
// 저장
let task = LocalOnlyQsTask(name: "Do laundry")
try! localRealm.write {
localRealm.add(task)
}
// Get all tasks in the realm
let tasks = localRealm.objects(LocalOnlyQsTask.self)
// You can also filter a collection
let tasksThatBeginWithA = tasks.where {
$0.name.starts(with: "A")
}
print("A list of all tasks that begin with A: \(tasksThatBeginWithA)")
// All modifications to a realm must happen in a write block.
let taskToUpdate = tasks[0]
try! localRealm.write {
taskToUpdate.status = "InProgress"
}
// All modifications to a realm must happen in a write block.
let taskToDelete = tasks[0]
try! localRealm.write {
// Delete the LocalOnlyQsTask.
localRealm.delete(taskToDelete)
}
5.모델 정의
//@Persisted var value: <Type>
//@Persisted var value: Data()
//@Persisted var value: Date()
//ex.
//Dog - 테이블 이름
//@Persisted - 컬럼
class Dog: Object {
@Persisted var name = ""
@Persisted var currentCity = ""
@Persisted var citiesVisited: MutableSet<String>
@Persisted var title: String
//PK 지정 - 중복X 필수값 => ObjectID
@Persisted(primaryKey: true) var objectID: ObjectID
}
6.PK지정
class Project: Object {
@Persisted(primaryKey: true) var id = 0
@Persisted var name = ""
}
7.스키마 경로 확인
// Get on-disk location of the default Realm
let realm = try! Realm()
print("Realm is located at:", realm.configuration.fileURL!)
-단순 확인용으로 viewDidLoad에 작성하여 앱 실행과 동시에 경로가 표시되도록 할 수 있다.
[SeSAC] 20220823_TIL (Realm 필터링, 정렬 ) (0) | 2022.08.23 |
---|---|
[SeSAC] 20220816_TIL (Custom Framework, Access Control, UIView Animation, PageViewController) (0) | 2022.08.16 |
[SeSAC] 20220811_TIL (Privacy & Authorization, 권한, Apple Map, MapKit) (0) | 2022.08.11 |
[SeSAC] 20220809_TIL (TableView + CollectionView) (0) | 2022.08.09 |
[SeSAC] 20220808_TIL (API관련 파일 관리하기) (0) | 2022.08.08 |