简体   繁体   中英

In Objective-C, what's the advantage of having a singleton over a class method?

如上所述,但是要小心,我只对Objective-C上下文感兴趣,因此没有必要指出单例优于静态方法的优点。

I would say nothing. Singletons are often considered bad practice and this applies to Obejctive-C as well. One thing that might make singletons a better solution than class methods is that singletons are proper instances that can access instance variables, so if one needs the class to store data in ivars, singletons can be a solution. (But well, even implementing singletons often requires using static global or local variables - so strictly speaking, you can't really avoid them entirely, at most you can reduce their number to one.)

One significant advantage is class methods in Objective-C can't hold onto any data (unless declared as static within the method). Whereas with a singleton, you have access to all of the data of the single-instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM