Are iVar declarations inside a header file's @interface braces strong or weak in iOS?

StackOverflow https://stackoverflow.com/questions/23686534

  •  23-07-2023
  •  | 
  •  

문제

Is the following declaration and call a strong or weak reference? I know that a strong reference inside an NSNotificationCenter block can lead to a retain cycle, so I'm trying to avoid that.

Declaration:

@interface MPOCertifiedAccountsViewController : MPORootViewController <UITableViewDataSource, UITableViewDelegate> {

    UITableView *certifiedTableView;
}

Call:

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

    if (self) {

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

                                                          [certifiedTableView reloadData];

                                                      }];
    }

    return self;
}
도움이 되었습니까?

해결책

All instance variables are by default strong. However, that is not relevant here because

[certifiedTableView reloadData];

is in fact

[self->certifiedTableView reloadData];

and that retains self, not the instance variable. So you have a retain cycle here, independent of whether certifiedTableView is a strong or weak instance variable.

You can solve that with the well-known technique of creating a weak reference to self:

__weak typeof(self) weakSelf = self;

which is used in the block:

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

You should also consider to use a property instead of an instance variable. With self.certifiedTableView you see immediately that self is retained.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top