Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Swift] Realm 사용해보기 #67

Closed
seungchan2 opened this issue Jun 1, 2022 · 0 comments
Closed

[Swift] Realm 사용해보기 #67

seungchan2 opened this issue Jun 1, 2022 · 0 comments
Assignees
Labels

Comments

@seungchan2
Copy link
Owner

1. Realm 설치 (SPM, Cocopods, Carthage 모두 가능)

pod init

.Podfile에 가시거나 vi 사용해서 설치 ㄱㄱ
pdd 'RealmSwift', '~>10'

pod install

2. RealmModel 만들기

import Foundation
import RealmSwift

//UsedDiary: 테이블 이름
//@Persisted: 컬럼

1. 저장하고 싶은 데이터가 총 5가지. 필수, 옵션으로 나누어 타입을 설정해줌
class UserDiary: Object {
   @Persisted var diaryTitle: String // 제목 (필수)
   @Persisted var content: String? // 내용 (옵션)
   @Persisted var writeDate = Date() // 날짜 (필수)
   @Persisted var registerDate = Date() // 등록일 (필수)
   @Persisted var favorite: Bool // 즐겨찾기 기능 (필수)
   
2. primaryKey를 설정
   // PK 필수: Int, String, UUID, ObjectID -> AutoIncrement
   @Persisted(primaryKey: true) var _id: ObjectId
   
   convenience init(diaryTitle: String, content: String?, writeDate: Date, registerDate: Date) {
       self.init()
       
       self.diaryTitle = diaryTitle
       self.content = content
       self.writeDate = writeDate
       self.registerDate = registerDate
       // 초기값을 false로 할당
       self.favorite = false
   }
}

3. 데이터를 Read 할 ViewController로 이동

import UIKit
// 1번
import RealmSwift

class WriteViewController: UIViewController {
    
    @IBOutlet var titleTextField: UITextField!
    @IBOutlet var contentTextView: UITextView!

// 2번 : Realm 파일에 접근하는 상수 선언
// Open the local-only default realm
    let localRealm = try! Realm()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("Realm is located at:", localRealm.configuration.fileURL!)
    }
    
    @IBAction func dismissHome(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func touchSavedButton(_ sender: UIButton) {

// 3번 : Realm 에 데이터 저장
        let task = UserDiary(diaryTitle: titleTextField.text!, content: contentTextView.text!, writeDate: Date() , registerDate: Date() )
        try! localRealm.write {
            localRealm.add(task)
        }
        print(task)
    }
    
}

4. 저장한 데이터 Scene에 보여주기

import UIKit
// 1번
import RealmSwift

class SearchViewController: UIViewController {

// 2번 : Realm 파일에 접근하는 상수 선언
    let localRealm = try! Realm()
    
// 3번 : Realm에서 읽어온 데이터를 담을 배열 선언
    var tasks : Results<UserDiary>!
    
    @IBOutlet var searchTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
   
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
 // 4번 : 배열에 Realm의 데이터 초기화
        tasks = localRealm.objects(UserDiary.self)
        print(tasks)
    }
    
    private func assignDelegate() {
        searchTableView.delegate = self
        searchTableView.dataSource = self
    }
    
    private func registerXib() {
        let nibName = UINib(nibName: "SearchTableViewCell", bundle: nil)
        searchTableView.register(nibName, forCellReuseIdentifier: "SearchTableViewCell")
    }

}

extension SearchViewController: UITableViewDelegate {
    
}

extension SearchViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = searchTableView.dequeueReusableCell(withIdentifier: "SearchTableViewCell") as? SearchTableViewCell else { return UITableViewCell()}
// 5번 : 테이블뷰에 데이터 표현      
        let row = tasks[indexPath.row]
        cell.contentLabel.text = row.content
        cell.dateLabel.text = "\(row.writeDate)"
        cell.titleLabel.text = row.diaryTitle
        
        return cell
    }
    
    
}

스크린샷 2022-06-01 오후 4 02 00

MongoDB에 실시간으로 데이터가 생성

스크린샷 2022-06-01 오후 4 02 47

@seungchan2 seungchan2 added the iOS label Jun 1, 2022
@seungchan2 seungchan2 self-assigned this Jun 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant