ios - 从 Objective-C block 访问分配委托(delegate)属性? (iOS)

标签 ios ios4 objective-c-blocks

可以从 block 访问委托(delegate)属性吗?

@interface TheObject : NSObject
...
@property (nonatomic, assign) id<SomeDelegate> delegate;

@synthesize delegate

- (void) someMethod {
  [someObject doSomethingWithCompletionHandler:^(NSArray *)someArray {
      [self.delegate otherMethod:someArray];   
 }];
}

如果在调用完成处理程序之前委托(delegate)被置空(通过也设置委托(delegate)的对象中的 dealloc 方法),会发生什么情况? 会不会是内存错误? 我不知道如何使用 __block 属性...

下面的答案:

如果委托(delegate)从作为 dealloc 调用委托(delegate)的对象中被清除,则一切都很好。

@property (nonatomic, retain) TheObject theObject;

@synthezise theObject = _theObject;

- (void) thatMethod {
  self.theObject = [[TheObject alloc] init] autorelease];
  _theObject.delegate = self;
}

- (void) dealloc {
  _theObject.delegate = nil;
  self.theObject = nil;
}

最佳答案

通常,如果您的委托(delegate)在执行该 block 之前被释放,那么它将访问垃圾,因为该 block 是一个分配属性并且该 block 保留 self 而不是 delegate,因为您通过引用访问它。

但是,由于您已将其设置为在 delegate 被释放时 self.delegate 被清空,所以您不会遇到这个问题。相反,如果您的委托(delegate)被释放,那么在您的代码中您只需将otherMethod:方法发送到nil,这不会执行任何操作,但也不会导致错误。

如果您希望该方法明确发送给您的委托(delegate),解决方案是通过值而不是引用来访问它:

- (void)someMethod {
    id <SomeDelegate> delegateForBlock = self.delegate;
    [someObject doSomethingWithCompletionHandler:^(NSArray *)someArray {
        [delegateForBlock otherMethod:someArray];   
    }];
}

这样 delegateForBlock 将是指向与 self.delegate 相同的对象的指针(在执行 someMethod: 时),并且它将被保留。

要了解有关其工作原理的更多信息,请查看 Blocks Programming Topics .

关于ios - 从 Objective-C block 访问分配委托(delegate)属性? (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428461/

相关文章:

objective-c - 强制提供完成 block

ios - 为什么 "loadNibNamed"方法返回数组?

iphone - block 返回错误

ios - Google Maps SDK iOS 以编程方式更改楼层

iphone - 如何从我的应用程序访问 "Manage Subscriptions"

objective-c - UIViewController 可见回调

iphone - strong(在 LLVM 中)和 retain(在 GCC 中)有什么区别?

Objective-C 为什么需要 __NSGlobalBlock__

ios - 键入时 TextView 中的 AttributedText

ios - UIWindow 添加 subview 有什么缺点?