Objective-C:修饰符与关键字

Page content

形容词用不好是会挨揍的

一个问题

delegate的修饰符使用weak还是使用strong?有没有特殊情况?

dekegate的修饰符通常情况下使用weak:

P对象是C对象的delegate,这一情况下,P对象持有C对象,C对象又通过delegate对P对象有引用,那么必须是weak弱引用,才可以避免循环引用。

特殊情况

让我们来看一下特殊情况,API中关于NSURLConnection的初始化函数:

~~~objective-c
- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate startImmediately:(BOOL)startImmediately NS_DEPRECATED(10_5, 10_11, 2_0, 9_0, "Use NSURLSession (see NSURLSession.h)") __WATCHOS_PROHIBITED;
~~~

对于这个API的官方描述说明如下:

Returns an initialized URL connection and begins to load the data for the URL request, if specified.

During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.

加粗部分强调的是这里的delegate是一个strong引用。这也是一个很好的特例。

strong修饰delegate属性一定会产生循环引用,那么为什么这里要使用strong呢?

这种用法肯定不是苹果的疏漏,而是有意为之,目的就是让发送网络请求的对象只有一个,即单例。

通过这种API设计来决定开发者所用的设计模式,是一种很高明的手段,这也是在AFNetworking中,manager设计为单例的原因。