iOS 프로그래밍 실무 11주차
2025. 5. 14. 16:44ㆍ📱 모바일 프로그래밍/iOS 프로그래밍 실무
struct MovieData : Codable {
let boxOfficerResult : BoxOfficeResult
}
struct BoxOfficeResult : Codable {
let dailyBoxOfficeList : [DailyBoxOfficeList]
}
struct DailyBoxOfficeList : Codable {
let movieNm: String
let audiCnt : String
let audiAcc : String
let rank : String
}
구조체 설명
- MovieData
- 최상위 구조체.
- boxOfficeResult라는 필드를 가짐.
- Codable 프로토콜을 채택해서, JSON 데이터로부터 자동으로 변환(디코딩, 인코딩) 가능.
- BoxOfficeResult
- dailyBoxOfficeList라는 배열을 가짐.
- 실제로 여러 영화의 일별 박스오피스 데이터가 이 배열 안에 들어감.
- DailyBoxOfficeList
- 영화 한 편의 일별 박스오피스 데이터(정보).
- 필드:
- movieNm: 영화 이름 (String)
- audiCnt: 당일 관객 수 (String)
- audiAcc: 누적 관객 수 (String)
- rank: 박스오피스 순위 (String)
용도
- JSON 형태로 된 영화 박스오피스 데이터를 받아서, Swift 앱(예: 아이폰 앱)에서 쉽게 사용하기 위해 구조체로 매핑.
- Codable 덕분에 데이터를 자동으로 변환할 수 있음.
https://developer.apple.com/documentation/foundation/jsondecoder
JSONDecoder | Apple Developer Documentation
An object that decodes instances of a data type from JSON objects.
developer.apple.com
func decode<T>(T.Type, from: Data) throws -> T
1. 어떤 함수야?
이 함수는 Data(데이터)를 내가 원하는 타입(T)으로 변환(디코딩) 해주는 함수예요.<br> 보통 JSON 데이터를 앱에서 사용하려고 Swift의 구조체, 클래스 등에 넣을 때 사용해요.
2. 어디서 써?
주로 JSONDecoder에서 쓰는 함수예요.
예시:
let decoder = JSONDecoder()
let myMovie = try decoder.decode(MovieData.self, from: jsonData)
여기서 decode가 바로 이 함수예요!
3. 함수의 전체모양
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
4. 각 부분 의미
부분 | 의미 |
decode | 함수 이름 (디코딩한다는 뜻) |
<T> | 제네릭(아무 타입에나 쓸 수 있게 함) |
(_ type: T.Type, from data: Data) | 입력값. <br>- type: T.Type: 어떤 타입으로 변환할지 <br>- from data: Data: 변환할 데이터 |
throws | 에러가 발생할 수 있음 |
-> T | 결과로 타입 T를 반환함 |
- decode 함수는 "Data를 내가 원하는 타입(T)으로 바꾼다"는 함수
- 어디서 자주 쓰냐면, JSON 데이터를 내 구조체나 클래스에 읽어넣을 때 사용함
- 사용법은 보통 decode(타입.self, from: 데이터)

예외 처리 해라

클로저 안에서 밖에 있는 프로퍼티에 접근하려면 self. 써줘야함

- Main Thread Checker: Xcode/iOS가 UI 관련 규칙을 잘 지키는지 검사하는 진단 도구.
- UI API called on a background thread: "UI 관련 함수가 백그라운드 스레드(메인 스레드 아님)에서 호출되었다."
- -[UITableView reloadData]: UITableView의 reloadData 라는 메서드를 잘못된(백그라운드) 스레드에서 호출했다는 뜻.

JSON 형태의 박스오피스 데이터를 API로 받아와 파싱(JSON 디코딩)한 뒤, 테이블 뷰에 영화 이름을 표시

Stack View


stack view 안에 stack view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell
cell.movieName.text = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].movieNm
cell.audiAccumulate.text = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].audiAcc
cell.audiCount.text = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].audiCnt
return cell
}
↓
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell
guard let mRank = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].rank else {
return UITableViewCell()}
guard let mName = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].movieNm else {
return UITableViewCell()}
cell.movieName.text = "[\(mRank)위] \(mName)"
if let aCnt = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].audiCnt {
let numF = NumberFormatter()
numF.numberStyle = .decimal
let aCount = Int(aCnt)!
let result = numF.string(for: aCount)!+"명"
cell.audiCount.text = "어제: \(result)"
}
if let aAcc = movieData?.boxOfficeResult.dailyBoxOfficeList[indexPath.row].audiAcc {
let numF = NumberFormatter()
numF.numberStyle = .decimal
let aAcc1 = Int(aAcc)!
let result = numF.string(for: aAcc1)!+"명"
cell.audiAccumulate.text = "누적: \(result)"
}
return cell
}
출처: iOS 프로그래밍 실무 강의 자료
'📱 모바일 프로그래밍 > iOS 프로그래밍 실무' 카테고리의 다른 글
iOS 프로그래밍 실무 14주차 (0) | 2025.06.04 |
---|---|
iOS 프로그래밍 실무 12주차 (0) | 2025.05.21 |
iOS 프로그래밍 실무 10주차 (1) | 2025.05.07 |
iOS 프로그래밍 실무 9주차 (1) | 2025.05.02 |
iOS 프로그래밍 실무 7주차 (1) | 2025.04.16 |