[ios] Swift 4 Singleton inheritance
Swift 4 에서 싱글톤 객체를 사용하는 방법은 여러 가지가 있겠지만 이건 내가 자주 사용하는 두 가지..
# 변수 형태로 사용하기
ex) Singleton.shared.name = "Hello"
클래스를 상속 받아서 확장하기 어려움 ㅠㅠ
import UIKit
class Singleton
{
static let shared: Singleton = {
var instance = Singleton()
instance.name = "default name"
return instance
}()
var name: String = String()
}
class SingletonSubclass: Singleton {
static var sharedSub: SingletonSubclass = {
var instance = SingletonSubclass()
instance.name = "default name"
return instance
}()
var title: String = String()
}
Singleton.shared.name // ""
SingletonSubclass.shared.name // ""
SingletonSubclass.shared.name = "haha"
SingletonSubclass.sharedSub.title = "hello"
Singleton.shared.name // ""
//Singleton.shared.title // (error)
SingletonSubclass.shared.name // "haha"
SingletonSubclass.sharedSub.title // "hello"
# 함수 형태로 사용하기
ex) Singleton.sharedInstance().name = "Hello"
클래스를 상속 받아 확장하기 편함
Sometimes you need to subclass your singleton…
import UIKit
class Singleton
{
class func sharedInstance() -> Singleton {
struct inner { static let instance = Singleton() }
inner.instance
return inner.instance
}
var name: String = String()
}
class SingletonSubclass: Singleton
{
override class func sharedInstance() -> SingletonSubclass {
struct inner { static let instance = SingletonSubclass() }
return inner.instance
}
var title: String = String()
}
Singleton.sharedInstance().name // ""
SingletonSubclass.sharedInstance().name // ""
SingletonSubclass.sharedInstance().name = "haha"
SingletonSubclass.sharedInstance().title = "hello"
Singleton.sharedInstance().name // ""
//Singleton.sharedInstance().title // (error)
SingletonSubclass.sharedInstance().name // "haha"
SingletonSubclass.sharedInstance().title // "hello"
번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|---|
1165 | Develop |
GCM 사용하기 2 (단말에 GCM 구현하기)
![]() |
hooni | 2013.07.06 | 24652 |
1164 | Develop |
GCM 사용하기 3 (JSP로 GCM 푸시 서버 만들기)
4 ![]() |
hooni | 2013.07.06 | 27129 |
1163 | Develop | git 브런치 배우기 (링크) | hooni | 2013.07.09 | 22079 |
1162 | Develop |
GPL, AGPL, MPL,.. 한눈에 보는 오픈소스SW 라이선스
![]() |
hooni | 2014.10.14 | 2062 |
1161 | Etc | GSM에서 음성이 실리는 과정 요약.. | hooni | 2013.04.23 | 18627 |
1160 | Etc | How to completely Uninstall Coda | hooni | 2017.10.24 | 4883 |
1159 | System/OS |
How to Install and Use wget on Mac
![]() |
hooni | 2020.09.03 | 5584 |
1158 | System/OS | How to Setup an Email Server on CentOS 7 | hooni | 2018.04.05 | 5912 |
1157 | Develop | How to Test SMTP AUTH using Telnet | hooni | 2018.04.05 | 6214 |
1156 | System/OS | HTTP 프로토콜 (브라우저와 웹서버 간의 통신) | hooni | 2003.04.23 | 50776 |
1155 | System/OS |
HTTPS와 SSL 인증서
![]() |
hooni | 2014.03.11 | 8756 |
1154 | Etc | iOS 에서 쓸만한 오프라인 구글지도 찾기 | hooni | 2014.01.06 | 17284 |