简体   繁体   中英

weakSelf & Delegate

As we know, we will declare a delegate object with weak that can break strong reference cycle:

// MyObject.h

...

@property (nonatomic, weak) id<MyDelegate> delegate;

...

// ViewController.m

...

 self.myObject.delegate = self;

...

and I want to know: can we declare delegate with strong, and set a weakSelf to it:

// MyObject.h

...

@property (nonatomic, strong) id<MyDelegate> delegate;

...

// ViewController.m

...

__weak typeof(self) weakSelf = self;
self.myObject.delegate = weakSelf;

...

据我所知,声明一个弱对象意味着您不拥有该对象,因此为其分配强委托是行不通的。

A delegate is a common design pattern used in Cocoa and CocoaTouch frameworks, where one class delegates responsibility for implementing some functionality to another. This follows a principle of separation of concerns, where the framework class implements generic functionality while a separate delegate instance implements the specific use case.

Delegate properties being weak is a recommendation to help avoid retain cycles.For explaination check @Bary Walk ans here . However, there are use cases where a strong reference is preferred, or even necessary. Apple uses this in NSURLConnection: 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.Check this previous SO ques for reference.

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