让我们说我有一个类实用程序方法,它初始化一个对象,分配它的委托并终止。
是否有任何方法可以保留该委托,以便它不会被释放导致message sent to deallocated instance
错误?
我理解委托对象被委托对象弱引用以避免保留周期(因为委托对象通常已经具有对委托对象的强引用)。
在我的情况下,我的委托对象在初始化之后不需要保留对委托对象的引用(我认为),所以我避免了保留周期的可能性。
所以我的问题是,ARC中是否有任何方法可以设置对象的委托(例如UIAlertView)并指定 它保留 委托,并在它不再使用时释放它(例如,当控制到达UIAlertView委托方法的末尾时)?
如果有帮助,请参阅以下代码示例:
+ (void)doSomethingWithCallback:(void(^)(void))callback
{
UIAlertViewDelegateWithBlock *delegate = [UIAlertViewDelegateWithBlock new];
delegate.callback = callback;
[[[UIAlertView alloc] initWithTitle:@"Alert" message:@"Hello World." delegate:delegate cancelButtonTitle:@"Cancel" otherButtonTitles:nil] show];
}
UIAlertViewDelegateWithBlock
就是这样:
@interface UIAlertViewDelegateWithBlock : NSObject <UIAlertViewDelegate>
@property (strong, nonatomic)void(^callback)(void);
@end
@implementation UIAlertViewDelegateWithBlock
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
self.callback();
}
@end
顺便说一句,如果委托对象返回对调用者的强引用,则保留委托并且我没有错误。但是,使用仅用于创建对委托的强引用的变量是不好的做法。