WeatherApp Project (4)

ulls12·2024년 2월 15일
0

Swift TIL

목록 보기
41/60

AppDelegate 의 변수 활용하기

처음 파일을 생성할 때, CoreData를 체크하고 생성을 하게 되면, AppDelegate.swift 파일에 Core Data와 관련된 메서드와 속성들이 추가된다. 그 중에는 persistentContainer 의 역할을 지정해준 코드가 들어 있다. 그렇다면, CoreDataManager.swift에서 따로 추가로 persistentContainer 의 역할을 지정해줄 필요 없이, AppDelegate에 지정된 변수를 불러내면 된다.

var persistentContainer: NSPersistentContainer? {
    (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
    }
// 타입 캐스팅을 해준 후, persistentContainer을 지정해준다.

타입 캐스팅을 통해, 코드를 축약 시킬 수 있고, 가독성이 높아지게 된다. 특이한 점은, shared 라는 변수를 따로 써주지 않아도 UIApplication은 자동으로 싱글톤 패턴으로 변한다는 것이다.

CoreData - UI View 바인딩

CoreData에서 객체를 저장하고 다시 로드하는 기능은 구현을 시켰다. 다만, API를 통해 받아온 위도와 경도의 데이터를 Core Data에 묶어내는 작업이 필요했다. 두 가지 방법이 있다.
1. CoreData를 관리하는 파일에서 Context 전달

func saveCoordinate(_ coordinate: Coordinate) {
   let lat = coordinate.lat ?? 0.0
   let lon = coordinate.lon ?? 0.0

       // Core Data에 저장할 MapData 객체 생성
       createMapData(lat: lat, lon: lon)
   }


// API응답 처리 코드에서 좌표 데이터를 CoreData에 넣는 코드
CoreDataManager.shared.saveCoordinate(coordinate)

결론적으로 검색창에서 검색을 통해 API를 통신할 때, 자동으로 데이터가 Core Data에 저장되고, View에서는 CoreData에 Read 메서드를 불러와 주면 된다.
2. CoreData가 필요한 VC에서 Context 전달
우선, MapData라는 Class와 CoreData메서드들을 직접 연결시켜줘야 한다. 그렇기 때문에, 코드 리팩토링이 필요했다. 저장된 데이터를 읽어주는 메서드의 반환 타입을 NSManagedObject 에서 설정한 Entity 값으로 바꿔주었다.

func readMapData() -> [MapData] {
    var mapData = [MapData]()
    do {
        let data = try context.fetch(request)
        mapData = data
    }catch{
        print("Error readdata :\(error)")
    }
    return mapData
}

//VC에서 저장된 데이터를 리로드하는 메서드
private func getCoreData(){
    let coreDataList = CoreDataManager.shared.readMapData()
    for data in coreDataList{
        ForecastAPIManger.shared.getForecastData(from: Coordinate(lat: data.lat, lon: data.lon)) { forecastInfoModel in
            DispatchQueue.main.sync {
                self.forecastInfoArr.append(forecastInfoModel)
               self.mainCollectionView.reloadData()
            }
        }
    }
}
//VC에서 추가 버튼을 눌렀을 때, 새로운 데이터를 저장하는 메서드
@objc func tapPlusButton(){
    CoreDataManager.shared.createMapData(lat: (forecastInfo?.coord.lat)!, lon: (forecastInfo?.coord.lon)!)
    addActionDelegate?.sendForecastInfo(data: forecastInfo!)
    dismiss(animated: true)
}

VC에서 CoreData와 API에서 각각의 위도와 경도에 대한 속성값들을 이어주는 작업을 진행해주면 된다.

profile
I am 개발해요

0개의 댓글