强与弱 - 如何定义可能连接或不连接到 IBOutlet 的 属性?

Strong vs weak - How to define a property that may or may not be connected to a IBOutlet?

我正在编写一个可重用的 class,它有一个 UITableView 属性 作为 IBOutlet。但是,我希望 class 在未连接到 xib 时创建一个 UITableView,因此为 nil。如果我将它设置为 weak,则以编程方式分配 UITableView 似乎不起作用。但是,如果我让它变得强大,那么如果使用 xib,它不一定会正确解除分配。处理这种情况的最佳方法是什么?

当作者知道其他人保留该对象时,属性通常被声明为弱。一个很好的例子是一个视图控制器,它希望保留指向其主视图的子视图的指针。主视图的子视图集合是一个数组,数组保留其元素(sub-sub-views以此类推)。

因此,将您的 table 视图声明为弱视图是正确的,无论它是否是通过 IBOutlet 设置的。但是初始化一个弱指针需要一些技巧,这样你就可以先建立一个与对象的保留关系,然后再对弱指针进行赋值 属性.

演示:

// assumes
@property(weak, nonatomic) IBOutlet UITableView *tableView;

- (void)viewDidLoad {
    [super viewDidLoad];

    if (!self.tableView) {  // if the outlet was not setup in IB
        // declare a stack variable that will be retained within the scope of this condition
        UITableView *tableView = [[UITableView alloc] init];
        // do whatever is needed to configure the tableView pointed to by this stack variable

        // this is key, make it a subview (establishing a retained relationship with subviews) first
        [self.view addSubview:tableView];
        // now we can assign it to our weak property
        self.tableView = tableView;
    }
}