简体   繁体   English

自我和委托

[英]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. 委托是Cocoa和CocoaTouch框架中使用的一种常见设计模式,其中一个类将负责实现某些功能的职责委托给另一个。 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 . 建议将代表属性设置为弱,以帮助避免保留周期。有关解释,请在此处检查@Bary Walk ans。 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. Apple在NSURLConnection中使用此方法:NSURLConnection实例只能使用一次。 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. 完成(失败或成功)之后,它将释放委托,并且由于委托是只读的,因此不能(安全)重用。请检查先前的SO查询以供参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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