Mar 15, 2021, TIL (Today I Learned) - Notification Center, iOS

Inwoo Hwang·2021년 8월 26일
0
post-thumbnail

수업 내용

야곰의 잔소리가 아닌 보약 소리


코드에 문서를 남기는 것을 지양하자.

  1. 코드만으로 이해할 수 있게 코드를 짜는게 낫다.
  2. 추후에 코드를 업데이트 하지 않을 경우에만 주석을 남기는 것이 좋다.
    • 나중에 코드를 작성할 때 바빠서 주석을 빼먹고 업데이트 안할 가능성이 높기에

구조체와 클래스의 차이


struct Person {
  var name: String
  var don: Int
  
  init(name: String, don: Int) {
    self.name = name
    self.don = don
  } 
// 구조체는 init이 생략되어도 된다. Memberwise initializer를 지원 해 주기 때문에!
// 클래스는 init이 무조건 있어야 한다.

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

🙋이니셜라이저는 왜 있어야 하는가?

"옵셔널 같은 경우 값이 없을 수 있음을 뜻한다. 반대로 옵셔널이 아니다는 값이 무조건 있음을 시사한다 또는 nil이 무조건 아니다를 뜻한다. 그 어떤 것이든 값이 있음을 보장 해 주어야 한다. 그래서 이런 맥락에서 initializer는 해당 프로퍼티의 값을 채워주는 역할을 한다."

Optional 외 모든 프로퍼티의 값을 채워주는 역할을 하는 것이 initializer의 의무이다.

따라서 클래스 내부에서 아예 default 초깃값을 주거나 init()을 활용하여 모든 프로퍼티 값을 채워줘야 한다.

그럼 왜 struct에만 멤버와이즈이니셜라이저가 지원되는가?

자세한 내용은 아래 링크에서 확인하자

Why don’t Swift classes have a memberwise initializer? - a free Understanding Swift tutorial (hackingwithswift.com)

Notification Center


인스턴스 사이의 통신[메시지 전달] 하는 방법 중 하나

Notification Center → Notification

  1. 사용자가 셀럽을 팔로우 [ 인스타그램 서버]
  2. 셀럽이 라이브방송을 할 때
  3. 해당 셀럽을 팔로우하는 팔로워에게 알림[Notification] 발송 → 셀럽 방송한다!!!

@objc 를 붙이는 이유 ↓

ios - When to use @objc in Swift? - Stack Overflow

class Stocker {
  let name: String
  init(name: String) {
    self.name = name
  }
	// !!매개변수 타입은 Notification타입이어야 한다!!
  @objc func follow(notification: Notification) {
    print("따라가요 \(her)를"
    
    if let userInfo = notification.userInfo {
      print("부가설명: " + userInfo.description)
    }
    
    NotificationCenter.default.removeObserver(self)
    // 위 메서드를 사용할 경우 더 이상 알림을 받지 않는다.
  }
}

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

// 알림 종류별 static property
enum CelebNotification {
  static let didRanOutHome = NSNotification.init("didCelebRanOutHome")
  static let willReturnHome = NSNotification.Name.init("willCelebReturnHome")
}

// 아래는 notification 등록과정
NotificationCenter.default.addObserver(ian, selector: #selector(Stocker.follow(notification:)), name: CelebNotification.didRanOutHome, object: nil)

NotificationCenter.default.addObserver(ian, selector: #selector(Stocker.follow(notification:)), name: CelebNotification.didRanOutHome. object: nil)
  
NotificationCenter.default.addObserver(ian, selector: #selector(Stocker.follow(notification:)), name: CelebNotification.didRanOutHome. object: nil)
// 셀럽이 나간다라는 행위를 이 스토커들은 구독하는 것과 같다.
// 셀럽이 나갈 경우 인스타 알림을 받듯이 위 스토커들에게 알람이 간다.

// 셀럽이 나갔다라고 방송 알림!!
Notification.default.post(name: name, object: nil)

Notification.default.post(name: name, object: nil, userInfo: ["name": "celeb", "address": "seoul", "time": "2021-03-03"] )
// 알림을 보낼 때 알릴 내용을 Dictionary형태로 같이 보낼 수 있다. 알림에 적을 내용을 디테일하게 적을 수 있다. 이 경우 두 번째 알림에만 해당 부가정보가 더해진다.

어떤 이벤트가 발생했는지 알림을 받는 것이 notification center이다.

1대1 통신이 아니라 여러 사람에게 해당 알림을 보내야할 경우 notification center를 사용한다.

능동적 알림방식

import Foundation

class Idol: NSObject {
    var name: String
    @objc var don: Int
    
    init(name: String, don: Int) {
        self.name = name
        self.don = don
    }
}

class Fan: NSObject {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(change)
    }
}

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

/// Key-Value-Observing

// 아래코드 수정필요
pengsu.observe(\.don, options:[NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old, NSKeyValueObservingOptions.initial]) { (idol, value) in
    print(idol)
    print(value)
}

pengsu.addObserver(summer, forKeyPath: "don", options: [NSKeyValueObservingOptions.new], context: nil)
// 펭수의 돈이 어떻게 바뀌는지 지켜본다.
// 첫 notification같은 경우 알림을 post해주는 notification center가 필요하다.
//그러나 key-value observing 같은 경우...
// 첫 notification과 달리 돈의 흐름을 파악할 수 있게 된다.
// 첫 notification은 중간매개체인 notification center가 필요하다. 그러나 후자 notification은 그런 중간 매개체가 필요없이 추적할 수 있다.

학습내용

iOS 앱개발 기초


@IBOutlet이란?

인터페이스 빌더에 올라와 있는 UI요소의 값을 가져오고 코드에 활용하고 싶을 때 사용하는 것

@IBAction이란?

인터페이스 빌더에 올라와 있는 요소의 이벤트를 받았을 때 그것에 반응하기 위해 action코드를 작성하기 위해 필요한 것

이벤트 기반 프로그래밍이란? [Event Driven Programming]

"A category of programming in which the flow of the app is determined by events: system events and user actions"

특정한 이벤트가 발생했을 때 특정 코드를 실행하겠다 정해 놓고 프로그래밍 하는 것이 이벤트 기반 프로그래밍!

Auto Layout이란?

"A layout engine that helps lay out user interface (UI) based on the constraints you specify"

Slider의 특징

Slider의 value 값은 항상 float만을 처리하도록 설계되어 있다. 따라서 Slider값을 할당하려면 float type으로 정수를 가공시켜줘야 한다.

profile
james, the enthusiastic developer

0개의 댓글