Skip to content

Commit d66e64e

Browse files
committed
fix: posts added
1 parent 1cf206a commit d66e64e

31 files changed

Lines changed: 3823 additions & 0 deletions

File tree

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
---
2+
title: Combine 프레임워크에서 에러 처리
3+
description: Combine에서의 에러 처리 방식과 주요 개념을 설명합니다.
4+
author: bbdyno
5+
date: 2025-02-24 22:04:03 +0900
6+
categories: [Development, iOS]
7+
tags: [Combine, ios, IOS개발, Swift, swift프로그래밍, 스위프트, 에러처리, 컴바인, 프로그래밍]
8+
pin: true
9+
math: true
10+
mermaid: true
11+
---
12+
Combine 프레임워크는 비동기 프로그래밍을 위한 도구이며, 데이터를 스트림 형태로 처리하는 데 유용합니다.
13+
14+
하지만, 네트워크 통신이나 데이터 처리 과정에서 예기치 않은 에러가 발생할 수 있기 때문에, 이를 적절하게 처리하는 것이 중요합니다.
15+
16+
이 글에서는 Combine에서의 에러 처리 방식과 관련된 주요 개념을 설명하겠습니다.
17+
18+
## 1. Combine에서 에러 처리 개요
19+
20+
Combine 프레임워크에서 `Publisher`는 성공(`Output`)과 실패(`Failure`) 두 가지 결과를 가질 수 있습니다. 실패 시, `Failure` 타입의 에러가 발생하며, 이는 `Publisher`의 타입 파라미터에서 명시됩니다.
21+
22+
```swift
23+
import Combine
24+
25+
enum NetworkError: Error {
26+
case invalidURL
27+
case requestFailed
28+
case decodingError
29+
}
30+
31+
let publisher = Fail<String, NetworkError>(error: .requestFailed)
32+
```
33+
34+
위 코드에서 `Fail`을 사용해 즉시 실패하는 `Publisher`를 생성할 수 있습니다.
35+
36+
## 2. 에러 이벤트를 처리하는 주요 Operator
37+
38+
Combine에서는 에러를 처리하기 위한 다양한 연산자(`Operator`)를 제공합니다. 대표적인 연산자는 다음과 같습니다.
39+
40+
### 2.1 `catch(_:)`
41+
42+
`catch(_:)` 연산자는 에러가 발생했을 때 대체 `Publisher`를 반환하여 에러를 처리합니다.
43+
44+
```swift
45+
let fallbackPublisher = Just("Fallback Value")
46+
.setFailureType(to: NetworkError.self)
47+
48+
let subscription = publisher
49+
.catch { _ in fallbackPublisher }
50+
.sink(receiveCompletion: { completion in
51+
print(completion)
52+
}, receiveValue: { value in
53+
print("Received value: \(value)")
54+
})
55+
```
56+
57+
출력 결과:
58+
59+
```
60+
Received value: Fallback Value
61+
finished
62+
```
63+
64+
### 2.2 `replaceError(with:)`
65+
66+
에러가 발생하면 특정 값으로 대체하는 방법입니다.
67+
68+
```swift
69+
let subscription = publisher
70+
.replaceError(with: "Default Value")
71+
.sink(receiveValue: { value in
72+
print("Received: \(value)")
73+
})
74+
```
75+
76+
출력 결과:
77+
78+
```
79+
Received: Default Value
80+
```
81+
82+
### 2.3 `retry(_:)`
83+
84+
에러 발생 시 지정된 횟수만큼 다시 시도하는 연산자입니다.
85+
86+
```swift
87+
let failingPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: "https://invalid.url")!)
88+
.map { $0.data }
89+
.decode(type: String.self, decoder: JSONDecoder())
90+
.retry(3) // 최대 3번까지 재시도
91+
.eraseToAnyPublisher()
92+
```
93+
94+
## 3. 에러 발생 시 Subscription 자동 취소
95+
96+
`cancel()`을 호출하지 않으면 `Subscription`이 지속될 수 있습니다. `Subscription`을 자동으로 취소하려면 `handleEvents(receiveCompletion:)`을 사용할 수 있습니다.
97+
98+
```swift
99+
let cancellable = publisher
100+
.handleEvents(receiveCompletion: { completion in
101+
if case .failure = completion {
102+
print("Cancelling subscription due to error")
103+
}
104+
})
105+
.sink(receiveCompletion: { _ in }, receiveValue: { _ in })
106+
```
107+
108+
또는 Combine의 `assign(to:on:)`을 활용하면 객체의 라이프사이클과 함께 자동으로 `Subscription`이 해제됩니다.
109+
110+
## 4. Combine과 Result 타입을 활용한 에러 처리
111+
112+
Combine에서 `Result<T, Error>` 타입을 함께 사용하면 보다 명확하게 에러를 전달할 수 있습니다.
113+
114+
```swift
115+
let publisher = Just("Success Value")
116+
.setFailureType(to: NetworkError.self)
117+
.map { Result<String, NetworkError>.success($0) }
118+
.catch { error in Just(Result.failure(error)) }
119+
.sink(receiveValue: { result in
120+
switch result {
121+
case .success(let value):
122+
print("Success: \(value)")
123+
case .failure(let error):
124+
print("Error: \(error)")
125+
}
126+
})
127+
```
128+
129+
이 방법을 사용하면, Combine 스트림에서 `Result` 타입을 반환하여 호출부에서 더욱 명확한 에러 핸들링이 가능합니다.
130+
131+
## 마무리
132+
133+
Combine에서의 에러 처리는 `catch`, `replaceError`, `retry` 등의 연산자를 적절히 활용하여 안정적인 스트림을 유지하는 것이 핵심입니다. 또한, `Subscription`을 자동으로 취소하는 방법과 `Result` 타입을 활용한 명확한 에러 처리 기법을 이해하면 더욱 효율적인 비동기 프로그래밍이 가능합니다.
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
---
2+
title: Core Data를 활용한 Data Migration
3+
description: Core Data에서 데이터 모델 변경 시 활용할 수 있는 마이그레이션 방법에 대해 알아봅니다.
4+
author: bbdyno
5+
date: 2025-02-24 21:52:00 +0900
6+
categories: [Development, iOS]
7+
tags: [CoreData, datamigration, ios, Swift, 개발, 데이터마이그레이션, 마이그레이션, 코어데이터]
8+
pin: true
9+
math: true
10+
mermaid: true
11+
---
12+
Core Data에서는 경량 마이그레이션(Lightweight Migration)과 무거운 마이그레이션(Heavyweight Migration)을 지원하며, 복잡한 마이그레이션을 위해 매핑 모델(Mapping Model)을 활용할 수도 있습니다.
13+
14+
## 1. Core Data 마이그레이션 개요
15+
데이터 모델이 변경되면 기존 데이터를 새로운 데이터 모델에 맞게 변환해야 합니다. Core Data는 이를 자동으로 처리할 수 있도록 다양한 마이그레이션 전략을 제공합니다.
16+
17+
### 마이그레이션이 필요한 상황
18+
- 엔터티(Entity) 이름 변경
19+
- 속성(Attribute) 추가/삭제
20+
- 관계(Relationship) 변경
21+
- 데이터 변환이 필요한 경우
22+
23+
## 2. 경량 마이그레이션 (Lightweight Migration)
24+
경량 마이그레이션은 Core Data가 자동으로 수행하는 방식으로, 비교적 단순한 변경 사항이 있을 때 사용됩니다.
25+
26+
### 지원하는 변경 사항
27+
- 속성 추가 및 삭제
28+
- 속성의 기본값 변경
29+
- 관계 추가 및 삭제
30+
- 엔터티 추가
31+
32+
### 설정 방법
33+
#### 1) 새로운 데이터 모델 버전 생성
34+
Xcode에서 `.xcdatamodeld` 파일을 열고 **Editor > Add Model Version**을 선택하여 새로운 모델 버전을 추가합니다.
35+
36+
#### 2) 코드에서 자동 마이그레이션 활성화
37+
38+
```swift
39+
let container = NSPersistentContainer(name: "MyApp")
40+
if let description = container.persistentStoreDescriptions.first {
41+
description.shouldMigrateStoreAutomatically = true
42+
description.shouldInferMappingModelAutomatically = true
43+
}
44+
45+
container.loadPersistentStores { (storeDescription, error) in
46+
if let error = error {
47+
fatalError("Unresolved error \(error)")
48+
}
49+
}
50+
```
51+
52+
이렇게 설정하면 Core Data가 변경 사항을 자동으로 감지하고 데이터를 마이그레이션합니다.
53+
54+
## 3. 무거운 마이그레이션 (Heavyweight Migration)
55+
경량 마이그레이션이 불가능한 경우 수동 마이그레이션을 수행해야 합니다. 예를 들어 다음과 같은 변경 사항이 있는 경우 무거운 마이그레이션이 필요합니다.
56+
57+
### 무거운 마이그레이션이 필요한 경우
58+
- 속성 타입 변경
59+
- 엔터티 이름 변경
60+
- 복잡한 데이터 변환
61+
62+
### 수동 마이그레이션 과정
63+
64+
#### 1) 매핑 모델(Mapping Model) 생성
65+
**File > New > Data Model Mapping Model**을 선택하여 `.xcmappingmodel` 파일을 생성합니다.
66+
67+
#### 2) 매핑 규칙 정의
68+
매핑 모델에서 소스 모델과 타겟 모델을 설정하고 속성 변환 규칙을 추가합니다.
69+
70+
#### 3) 마이그레이션 코드 작성
71+
72+
```swift
73+
let sourceURL = URL(fileURLWithPath: "sourcePath")
74+
let destinationURL = URL(fileURLWithPath: "destinationPath")
75+
76+
if let mappingModel = NSMappingModel(from: nil, forSourceModel: sourceModel, destinationModel: destinationModel) {
77+
let migrationManager = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel)
78+
79+
do {
80+
try migrationManager.migrateStore(
81+
from: sourceURL,
82+
sourceType: NSSQLiteStoreType,
83+
options: nil,
84+
with: mappingModel,
85+
toDestinationURL: destinationURL,
86+
destinationType: NSSQLiteStoreType,
87+
destinationOptions: nil
88+
)
89+
} catch {
90+
print("Migration failed: \(error)")
91+
}
92+
}
93+
```
94+
95+
## 4. 데이터 마이그레이션 시 발생할 수 있는 문제와 해결 방법
96+
97+
### 마이그레이션 실패 원인 및 해결 방법
98+
99+
| 실패 원인 | 해결 방법 |
100+
|-----------|----------|
101+
| 모델 변경 감지 실패 | `shouldInferMappingModelAutomatically = true` 설정 |
102+
| SQLite 파일 손상 | 기존 스토어 삭제 후 새로 생성 또는 백업 후 복원 |
103+
| 매핑 모델 오류 | `.xcmappingmodel` 수정 및 매핑 규칙 재정의 |
104+
105+
## 5. 예제 프로젝트
106+
107+
### 경량 마이그레이션 예제
108+
데이터 모델이 다음과 같이 변경되었다고 가정합니다.
109+
110+
#### 변경 전:
111+
```swift
112+
class User: NSManagedObject {
113+
@NSManaged var name: String
114+
}
115+
```
116+
117+
#### 변경 후:
118+
```swift
119+
class User: NSManagedObject {
120+
@NSManaged var name: String
121+
@NSManaged var age: Int16
122+
}
123+
```
124+
125+
위처럼 속성을 추가하는 변경은 경량 마이그레이션으로 처리할 수 있습니다. Xcode에서 자동으로 마이그레이션을 활성화하면 됩니다.
126+
127+
### 무거운 마이그레이션 예제
128+
만약 `name` 속성의 타입이 `String`에서 `Data`로 변경되었다면 무거운 마이그레이션이 필요합니다.
129+
130+
이 경우 매핑 모델을 사용하여 변환해야 합니다.
131+
132+
#### 변환 로직 구현:
133+
```swift
134+
class NameToDataTransformer: ValueTransformer {
135+
override func transformedValue(_ value: Any?) -> Any? {
136+
guard let string = value as? String else { return nil }
137+
return string.data(using: .utf8)
138+
}
139+
}
140+
```
141+
142+
이제 `NSMigrationManager`를 사용하여 직접 마이그레이션을 실행할 수 있습니다.
143+
144+
## 마무리
145+
Core Data 마이그레이션은 데이터 모델이 변경될 때 필수적으로 고려해야 하는 요소입니다. 경량 마이그레이션은 자동으로 수행되지만, 복잡한 변경이 있는 경우 무거운 마이그레이션을 수행해야 합니다. 특히 매핑 모델을 활용하면 보다 세밀한 마이그레이션이 가능합니다.
146+
147+
데이터 모델 변경이 필요할 경우 미리 마이그레이션 전략을 수립하여 원활한 데이터 이전을 보장하는 것이 중요합니다.

0 commit comments

Comments
 (0)