OGeek|极客世界-中国程序员成长平台

标题: ios - 在 iOS 中,头文件的 @interface 大括号内的 iVar 声明是强还是弱? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:50
标题: ios - 在 iOS 中,头文件的 @interface 大括号内的 iVar 声明是强还是弱?

下面的声明和调用是强引用还是弱引用?我知道 NSNotificationCenter block 内的强引用会导致保留周期,所以我试图避免这种情况。

声明:

@interface MPOCertifiedAccountsViewController : MPORootViewController <UITableViewDataSource, UITableViewDelegate> {

    UITableView *certifiedTableView;
}

调用:

- (id)init
{
    self = [super init];

    if (self) {

        [[NSNotificationCenter defaultCenter] addObserverForName:MPOFriendManagerManagerDidFinishRefreshingLocal
                                                          object:nil
                                                           queue:[NSOperationQueue mainQueue]
                                                      usingBlock:^(NSNotification *note) {

                                                          [certifiedTableView reloadData];

                                                      }];
    }

    return self;
}



Best Answer-推荐答案


默认情况下所有实例变量都是strong。但是,这与此处无关,因为

[certifiedTableView reloadData];

事实上

[self->certifiedTableView reloadData];

并且保留self,而不是实例变量。所以你在这里有一个保留周期, 与 certifiedTableView 是强实例变量还是弱实例变量无关。

您可以使用众所周知的创建对 self 的弱引用的技术来解决这个问题:

__weak typeof(self) weakSelf = self;

block 中使用的:

typeof(self) strongSelf = weakSelf;
if (strongSelf != nil) {
    [strongSelf->certifiedTableView reloadData];
}

您还应该考虑使用 属性 而不是实例变量。 使用 self.certifiedTableView 您会立即看到 self 被保留。

关于ios - 在 iOS 中,头文件的 @interface 大括号内的 iVar 声明是强还是弱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23686534/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4