티스토리 뷰

TIL

TIL ('21.03.15)

learner._.Kio 2021. 3. 16. 00:39

학습내용

잔소리

코드에 주석을 남기지마라

  • 코드만으로도 모든 걸 이해할 수 있게 작성하자
  • 코드가 업데이트 되면 문서화주석을 업데이트 해야한다. → 그럴거면 남기지 말라.

모든 걸 이해하지 못한다고 자괴감 들지마라

 

Struct vs Class init

Init은 옵셔널을 제외한 property의 값을 모두 채워주는 것이다.

Struct

struct Person {
    var name: String
    var don: Int

    // struct의 init은 생략되어 있다.
    init(name: String, don: Int) {
        self.name = name
        self.don = don
    }
}

var yagom = Person.init(name: "야곰", don: 0)

Class

방법1

class Person {
    var name: String
    var don: Int

    init(name: String, don: Int) {
        self.name = name
        self.don = don
    }
}

var yagom = Person.init(name: "야곰", don: 0)

방법2

class Person {
    var name: String = ""
    var don: Int = 0

}

var yagom = Person.init()
yagom.name = "yagom"
yagom.don = 100

 

Notification Center

Notification Center이란?

  • Notification Center은 post(= 발신,발송)를 해줘야 알 수 있다.
ex)
인스타에서 라이브방송을 열면 push로 온다
인스타에서 구독해놓은 사람의 게시물이 보인다.

코드로 표시한다면?

import Foundation

// 인스턴스 사이의 통신(메시지 전달)

/// Notification Center -> Notification

/*
 1. 강경이 Neph를 구독 (인스타그램 서버)
 1-1. Kio/Summer가 Neph를 구독
 2. Neph가 라이브 방송을 연다
 3. 강경/Kio/Summer한테 알림(notification)발송 -> Neph 방송함
*/

/*
// Notification Center -> 큐피드
 이안, 스티브, 라이언 -> 편의점에 바나나우유 알림설정하겠다(Notification Center)
 바나나우유가 들어온다.
 큐피드 -> 이안, 스티븐, 라이언: 바나나우유 지금 재고있다!!!
*/

class Enemy {
    let name: String
    init(name: String) {
        self.name = name
    }

    @objc func buyBananaMile(stock: Notification) {
        print("\(name)이 바나나우유를 사러가요 \(userInfo.description")
        NotificationCenter.default.removeObserver(self) // 방송해지
    }
}

let ian = Enemy(name: "이안")
let steven = Enemy(name: "스티븐")
let ryan = Enemy(name: "라이언")

enum popUpBananaMilkNotification {
}

let popUpBananaMilkNotification = NSNotification.Name.init("popUpBananaMilk")

NotificationCenter.default.addObserver(ian,
                                       selector: #selector(Enemy.buyBananaMile(stock:)),
                                       name: popUpBananaMilkNotification,
                                       object: nil)

NotificationCenter.default.addObserver(steven,
                                       selector: #selector(Enemy.buyBananaMile(stock:)),
                                       name: popUpBananaMilkNotification,
                                       object: nil)

NotificationCenter.default.addObserver(ryan,
                                       selector: #selector(Enemy.buyBananaMile(stock:)),
                                       name: popUpBananaMilkNotification,
                                       object: nil)

NotificationCenter.default.post(name: popUpBananaMilkNotification,
                                object: nil,
                                userInfo: ["name" : "Milk",
                                           "type" : "Strawberry",
                                           "time" : "2021-03-15 00:12:34"])

// 방송을 해지했기 때문에 1번만 방송함!
NotificationCenter.default.post(name: popUpBananaMilkNotification, object: nil)

 

KVO (Key Value Observing)

  • Notification Center은 post(= 발신,발송)를 해줘야 알 수 있다.
  • KVO는 실시간으로 알려준다. 계속 지켜보니까
lass Idol: NSObject {
      var name: String
      var money: Int

      init(name: String, money: Int) {
          self.name = name
          self.money = money
      }
  }

  class Fan: NSObject {
      var name: String

      init(name: String) {
          self.name = name
      }

      func observeValue(forKeyPath KeyPath: String?, of object)
  }

  let pengsu = Idol(name: "펭수", money: 100000000)
  let summer = Fan(name: "썸머")

  pengsu.obser
  pengsu.addObserver(summer,
                     forKeyPath: "Money",
                     options: [NSKeyValueObservingOptions.new],
                     context: nil)

  pengsu.money = 0
  pengsu.money = 100
  pengsu.money = 10000

Xcode 오류

A. Thread 1: signal SIGTERM

  1. 시뮬레이터를 끌 때는 cmd + Q로 끄자여태까지는 마우스로 X 클릭했는데 cmd + Q로 끄니까 오류가 안 나오듯 싶다. 아직까지는!
  2. https://www.youtube.com/watch?v=g51cw1ib7hs 댓글 참고
  3. Main.storyboard > ViewController > Connection Inspector
    • 노란 경고창 → 유효하지 않은 연결
      • 발생이유: 연결해놓은 method명을 변경했다는지 아니면 등등(??) 나도 모른다 아직 😱
    • ViewController가 2개 이상일 경우 위 사항을 각각 확인할 것.

 

alert.addAction

  • alert.addAction으로 2개도 연결할 수 있는 거였다...! 난 하나만 되는줄...
  • let alert = UIAlertController(title: "주문 실패", message: "재료가 모자라요. 재고를 수정할까요?", preferredStyle: UIAlertController.Style.alert) let okAction = UIAlertAction(title: "YES", style: .default, handler: nil) let noAction = UIAlertAction(title: "NO", style: .destructive, handler: nil) alert.addAction(okAction) alert.addAction(noAction) present(alert, animated: true, completion: nil)

 

style: .cancel / .destructive / .default

style: .cancel

  • 아니오가 먼저 앞으로 온다!
  • Bold체 적용!

let noAction = UIAlertAction(title: "아니오", style: .cancel, handler: nil)

style: .destrutive

  • 아니오를 빨강으로 하려고 찾아봤는데 color함수 만드는 거 하다가 포기했는데 hailey가 이걸 알려주었다. 이렇게 쉬웠다니... 😭

let noAction = UIAlertAction(title: "아니오", style: .destrutive, handler: nil)

style: .default

let noAction = UIAlertAction(title: "아니오", style: .default, handler: nil)

 

문제점 / 고민한 점 → 해결방법

  • ViewController.swif에서 재고를 어떻게 연결해야할지 고민
    • 하루종일 고민하다 Struct 인스턴스화로 겨우 했다. 일단은...!
  • alert.text color를 red로 하고 싶어서 찾은 건 함수 만들다가 포기
    • Hailey가 .destrutive 로 바로 해결... 빛 그 자체 ✨
  • @IBAction, @IBOutlet의 역할은?!

'TIL' 카테고리의 다른 글

TIL ('21.03.18) - iOS View Life Cycle  (0) 2021.03.18
TIL ('21.03.17)  (0) 2021.03.17
TIL ('21.03.12)  (0) 2021.03.14
TIL ('21.03.11)  (0) 2021.03.12
TIL ('21.03.09)  (0) 2021.03.10
댓글