单例与第三方库 [英] Singleton vs. third-party libraries
问题描述
我熟悉的概念单例,这种机制非常方便,但是..
如果我想要一个第三方类的共享实例会发生什么,例如AFHTTPRequestOperation
或者一些神奇的记录?
当我在多个控制器中使用来自外部类的一个对象时,我该怎么办?或者在每个控制器中实例化一个新对象可能是一个好习惯?
I'm familiar with the concept of Singleton and this mechanism is pretty handy but..
What happens in case I want one, shared instance of some third-party class e.g. AFHTTPRequestOperation
or maybe some Magical Record?
What should I do when I'm using one object from external class in many controllers? Or maybe it is a good practice to instantiate a new object in each controller?
推荐答案
我对 Magical Record
不熟悉,但对于 AFNewtorking
来说,制作单例绝对有意义在很多情况下.
I'm not familiar with Magical Record
but for AFNewtorking
it definitely makes sense to make a singleton in many cases.
虽然 AFHTTPRequestOperation
的单例听起来不太对.更好的候选者是 AFHTTPRequestOperationManager
.
Though singleton of AFHTTPRequestOperation
doesn't sound quite right. Much better candidate would be AFHTTPRequestOperationManager
.
引用自 AFHTTPRequestOperationManager 类参考
面向 iOS 7 或 Mac OS X 10.9 或更高版本的开发者鼓励广泛使用 Web 服务进行子类化AFHTTPSessionManager,提供一个类方法,返回一个共享的身份验证和其他配置可以在其上的单例对象在整个应用程序中共享.
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass AFHTTPSessionManager, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
对于面向 iOS 6 或 Mac OS X 10.8 或更早版本的开发者,AFHTTPRequestOperationManager 可以用来达到类似的效果.
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, AFHTTPRequestOperationManager may be used to similar effect.
它与 AFHTTPCLient
在 <2.0 版本中类似.
It was similar with AFHTTPCLient
in <2.0 versions.
一个很好的参考也是Scott Sherwood 的本教程(作为总是)Ray Wenderlich 博客.
One good reference would also be this tutorial by Scott Sherwood on (as always) Ray Wenderlich blog.
这篇关于单例与第三方库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!