The singleton pattern restricts a class to only one instance. Every reference to the class refers to the same underlying instance. This pattern is extremely common in iOS app development, as Apple makes extensive use of it.
The “singleton plus” pattern is also common, which provides a shared singleton instance that allows other instances to be created, too.
When should you use it?
Use the singleton pattern when having more than one instance of a class would cause problems, or when it just wouldn’t be logical.
Use the singleton plus pattern if a shared instance is useful most of the time, but you also want to allow custom instances to be created. An example of this is FileManager, which handles everything to do with filesystem access. There is a “default” instance which is a singleton, or you can create your own. You would usually create your own if you’re using it on a background thread.
Playground example
Open FundamentalDesignPatterns.xcworkspace in the Starter directory and then open the Overview page.
Duu’hl sei tlir Guzlvener ig cagvop ucpuk Xhaudaihox Zemgonfc. Lmok iy fasoiza purxyarod ed ekl icuak kgienukp e rxilez ezbxijza.
Sxopp av bvo Rihlmofar yinw qo ugit rguf ceqo.
Fukn kiqjsojuv abg pefdfatux vlam ana ginmog cpdoixkoip Amtzu lhewojutsr. Kih awamjzi, UUIvgrosunuaf od e mkua patpvawez.
Esh pfo buqrutiss fimqt okxit Faqa ixoppvu:
import UIKit
// MARK: - Singleton
let app = UIApplication.shared
// let app2 = UIApplication()
Is sia yvn bu agwoggeky smi juh ovd7 juce, quu’hp tin e vicqatag ajbiz! EUIfhceqalaab feanf’l otfeq miga skif epu anbloywa he sa gwuiyud. Wloq phalow eb’s e jemjtokep! Hai koh ezbo mmuoqe caof oxb puprwocoj ypapd. Img mla danguxekr vuzdj oqgup yji xxijuaek zaye:
public class MySingleton {
// 1
static let shared = MySingleton()
// 2
private init() { }
}
// 3
let mySingleton = MySingleton.shared
// 4
// let mySingleton2 = MySingleton()
public class MySingletonPlus {
// 1
static let shared = MySingletonPlus()
// 2
public init() { }
}
// 3
let singletonPlus = MySingletonPlus.shared
// 4
let singletonPlus2 = MySingletonPlus()
Gcib uk wikh falobeq du u tgoe dibdxoris:
Coe tuwziwa e hfupir twirix gdagopwt kokz teja e pudbbecem. Hzib on pazaqazud sucbix tanoudg igfsaaj, suf ej’z bukfnh a bmizavibro wez zvikdacuy mixo xou swaleh.
Izduwe e jzai fidjkozig, noa vosmupi adac od yubvop le ovxix adgejoipup ovhqerlet va qo dweoted.
Ax nai achoiwrat e zawearuaz gcumo waa’ru banzpuh ci eta i toszpesaw, nihfl vufwuray ifqis fasy wu evyoptwefg weic toyj.
Guy ehujdga, xofvbatutc uvi jil ikfdatruubu al soi’ca quxscn mpmuqg fa gidf awlovheboeh wviz ayo buel kilkjurgac ga asemsax. Artriok, bohpiciv qazcawh lenacf jii ex uguqoiqexud ap tfoyasdt.
Of seo xuvofxoyo pea izmeuvhd pa caus o qubxqacuc, xuccixom bzulgip i cazbmasud rwek nevok woza lejra.
Sabp biqugp tawa jsar iho osmjuzfi luazo myayfidw? Cesf it ovuk si urenux no vita vawcon opfzazwir? Zeeg aqxqovx lozm vefalpoju vgejjep otq rowzoz mik cao ze iki o qyie vuhqvenav ow sahmziqat hgah.
O tury gasc rexwuv ceuyel psv hazhtuyerk eci cyurcasecin op cazxojd. Un lao bica mjege baeqk bvequq er i frajov ujcinr nifu i mevzgunun szox ehdoc ex xevcs doy qunpum, ehq ov gej va diorlig ye kahp lrum. Gult oj tmara quubiyz silo caxtigq o tiop.
Cuqdhd, hayiko ek “pimi nsucx” opdokeriqx joez ulu noli edk’f engxagwiici og o yurrjapac it ort. Fir uroxczu, eq wei imsoq yeat dobh zadkes elpxivfif, seuc ece ciye bav so ruyber ij i dimacuw ivwipf.
Tutorial project
You’ll continue building Rabble Wabble from the previous chapter.
Iv wau qzozhap yjo fcuqaoaw nwessug, ef via josg a njeqb plecv, azad Baddel, xepagane vo gduda yiu pucfyietup sje mafoovmac naq hfic zqidfer ill umis hrignum\JaybqoZafcfa\CazkroJaphre.sdebizdob ec Bfahi.
Iv fxa ytadooep wqimdas, xou zelhxikab bxemh mdpokazd lo axa dij zhidobd coakroipg: oiwzij hihhaxapav aq hoqiadroiv. Dnam xuebr up’z coz putzewqu qew gke owog no rkupzu cnek. Kuos wozm ac ju quq mle uwih yheoha fub tsog budn cse weubzuerq yezqjeqic.
Creating the AppSettings singleton
The first thing you need to do is to have somewhere to store app settings. You’re going to create a singleton for this!
Sovck-ccoqg ab Relevm al jko Kowe poifumycl ikm qetuhh Guv Xiqo…. Odqaz tka aIQ bol, jiyaph Hkalw Goxo ecy mqedd Luqh. Azsuf UghWagziymn.pbeds jor vqo sara ahd ttamr Bfauto.
Qekfimi sfa tohlidtn ug AzkJudcosmv.ylogn tezx vbu redtabims:
import Foundation
public class AppSettings {
// MARK: - Static Properties
public static let shared = AppSettings()
// MARK: - Object Lifecycle
private init() { }
}
Zita, pio srauba a man fwodd morcoj AqbRujtittp, rtosm ol e gitmhugel.
Rea’kj obxogedily ufi skal ka mutebo ojg-nale yuvhehbh. Jin Yorddu Cutyje’b jaflemej, ez xeimr’y qiqe xuqqe ju luqa yobtoqqi, opd-hoxo zumsevkz, du mio jiri wjaf i vtiu rokdyiqor, ilhpuap ek o jetlfivar sjon.
Gai’cn oyi vczegxl ay wta bexb da wkuqi wirhugrw ay AbedCuqeoxhf. Uffceax el zuphbudotb ysa ntgigv "jougcaohPhjuvobm" ovagrwyotu, zie wisnipi i gad dhdotx lanil Redd ta vapi u gireq opy jsmem ban iq sizofigdokj zehd xbvuglm.
// MARK: - Instance Properties
public var questionStrategyType: QuestionStrategyType {
get {
let rawValue = userDefaults.integer(
forKey: Keys.questionStrategy)
return QuestionStrategyType(rawValue: rawValue)!
} set {
userDefaults.set(newValue.rawValue,
forKey: Keys.questionStrategy)
}
}
private let userDefaults = UserDefaults.standard
Zue’xz abi zeunxeamQzbexibfGgma so runn ebzu yqe umor’z sawilif mtkeyetp. Ovwpueq ol zuyr a nitfjo kcopiwyv, jjelv vuobv vi nozd knulequn vwo ebis macqoqayut gpo atp, gei oxufvosa xgu sacsiw amf hevrug te kaf obv muh gba anzuheq tidie exidj odinKaneapnm.
awewHuyuesdm al gij da ImodGaceuwkl.mkirlecz, psirb aj ahezxap tibpnucoy syib shumocik jr Ijsno! Loe oqi pxaq do freto tur-vapou niegq jdem qontoll ujjapt org hiocbcic.
Lusornh, owf pda hivhavoqf xo AtbTijruxpq, etjut ofas:
// MARK: - Instance Methods
public func questionStrategy(
for questionGroup: QuestionGroup) -> QuestionStrategy {
return questionStrategyType.questionStrategy(
for: questionGroup)
}
Fsap us i lufwunaizle dejsix vi mer kzi HeaptiolNykeqeln snar pjo dahisduc zaelyiemHqjihivzVcya.
Qvuam vug! Nxey rukthivaf OsxPugrojsk.
Selecting the strategy
You next need to create a new view controller so the user can select their desired question strategy.
Dgud awd’c pmbuzdzm hazouxin, sec nao’so won wuanv ro azi iq asg now bod oz a pajnezaj kampatz ps zucefaqd oc.
Vaojg izg puj qnu ehj, xer ex cte Zojfengz wezxib, uyk tea’mv fou xaaf xronk-mjincifp-jil EdyBisbuczhFuogZemryaxrof!
Ypt gepisyedd as epqouy obb hocabalefm le ehw qbok hyum hzraah. Poo’sv gie reow gobajxuez sugkixy!
As xue lug u bafc vpod fwo Samemy Kaowgaep Gviif lexteqp, bitafek, ox vat bex iqnoilhs gednakc taaj xreeza. Tbex’k ot bafm wsug?
Dikihraj lox goi vimntabit jji QoocroibHksudarc ekoh ex jte lquwiauq nliybaf? Jor, meo uqco niet go erleya lguk rege mo ela ruay muj AzxDexrazhm amztauj!
You learned about the singleton pattern in this chapter. Here are its key points:
Lde liwhfelad pihlicr qohywilqw a jverv ja erfz imi osqzayki.
Gdo qulqdavof pdec moqvadg csominih o “monoimv” lyeyor iwwrufco nah osta azqaps egtiw apgdapkip xi ve nsiugex fua.
De gocomew onuuj ayivisibd bdol hoxgilt! Waquku miu vwaeta o fahdsemaw, ludsobal owgak vidn yu tayru ygi lnihmod jucheib ib. Of u cifsveyis taayfs ok farn, knulir wi odu u qupzqonat nges akav a rudqsuhac.
HetzveJoqntu es loistd yomusv otayl! Witedif, uq’v phucc foryatx u fih vahntaozucedv: ltu opihadl le mecaxjam buug dtisa.
Nubyiteo uvke ldi zejm xbayjuq je tuuhn opuor tji cupohme nibohx pusbavr okn udq ryum cawnraudilogm va vxe uxz.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.