Is it ever Ok to have a 'strong' reference for a delegate?

前端 未结 4 535
Happy的楠姐
Happy的楠姐 2020-12-04 20:32

I have a class that retrieves JSON from a URL and returns the data via the protocol/delegate pattern.

MRDelegateClass.h

#import 

        
4条回答
  •  执念已碎
    2020-12-04 20:39

    You are correct in that delegates are usually weakly referenced. However, there are use cases where a strong reference is preferred, or even necessary. Apple uses this in NSURLConnection:

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

    An NSURLConnection instance can only be used once. After it finishes (either with failure or success), it releases the delegate, and since the delegate is readonly, it can't be (safely) reused.

    You can do something similar. In your dataRetrieved and dataFailed methods, set your delegate to nil. You probably don't need to make your delegate readonly if you want to reuse your object, but you will have to assign your delegate again.

提交回复
热议问题