안녕하세요!
계속해서 <뭐 먹지? 태그로 관리하는 맛집 & 룰렛>앱을 제작하며 사용한 코드를 설명하겠습니다.
오늘은 앱의 데이터를 어떻게 저장할까?를 고민하고 적용한 방법에 대한 소개입니다.
앱에서 맛집을 저장할 때 아래의 그림처럼 태그를 중분류 - 소분류로 나누어 저장합니다.
그래서 데이터 구조는 아래의 그림처럼 하나의 식당에 여러개의 태그가 들어가는 형식으로 처리되어야 했습니다.
태그가 몇개가 추가될지 알 수 없기 때문에 코어 데이터의 entity에 들어가는
태그에 해당하는 Attribute의 개수를 유동적으로 처리할 필요가 있었습니다.
그래서 entity를 식당에 관련된 데이터를 저장하는 RestaurantData entity와
태그 정보를 관리하는 CategoryData entity로 분리하였습니다.
그리고 RestaurantData entity와 CategoryData entity에 Relationships의 타입을
To Many로 설정하여 하나의 RestaurantData entity가 다수의 CategoryData entity를 가지도록 하였습니다.
아래는 코어 데이터로 맛집을 저장하는데 사용한 코드입니다.
RestaurantData entity를 코어 데이터로 저장하는 코드는 일반적인 방법과 같습니다.
이후 배열로 받아온 태그 데이터를 반복문을 통해 갯수만큼 새로운 객체를 생성해서
entity를 To Many로 설정하며 제공되는 .addTo 함수를 통해
RestaurantData에 CategoryData의 관계를 설정하였습니다.
func saveResToCoreData(address: String, group: String, phone: String, placeName: String, roadAddress: String, placeURL: String, date: Date, imagePath: String, categoryNameArray: [String], categoryTextArray: [String], competion: @escaping () -> Void) {
// RestaurantData의 entity 유효한지 확인
guard let entityRestaurant = NSEntityDescription.entity(forEntityName: entityName_Res, in: context) else {
competion()
return
}
// CategoryData의 entity 유효한지 확인
guard let entityCategory = NSEntityDescription.entity(forEntityName: entityName_Cat, in: context) else {
competion()
return
}
// 할당할 데이터를 가진 객체 생성
guard let newRes = NSManagedObject(entity: entityRestaurant, insertInto: context) as? RestaurantData else {
competion()
return
}
// 객체에 데이터 할당
newRes.address = address
newRes.group = group
newRes.phone = phone
newRes.placeName = placeName
newRes.roadAddress = roadAddress
newRes.placeURL = placeURL
newRes.date = date
newRes.imagePath = imagePath
// 카테고리 배열 할당
for index in 0...categoryNameArray.count - 1 {
// 할당할 데이터를 가진 객체 생성
guard let newCat = NSManagedObject(entity: entityCategory, insertInto: context) as? CategoryData else {
competion()
return
}
newCat.categoryName = categoryNameArray[index]
newCat.categoryText = categoryTextArray[index]
newCat.order = Int32(index)
// newMenu에 newCategory 더하기
newRes.addToCategory(newCat)
}
do {
try context.save()
competion()
} catch {
print(error)
competion()
}
competion()
}
++ 누적해서 정리한 내용은 깃허브에 올리고 있습니다. 링크