gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:14:15 25 4
gpt4 key购买 nike

我正在编写一个可重用的类,它有一个 UITableView 属性作为 IBOutlet。但是,我希望该类创建一个 UITableView(如果它未连接到 xib,因此为零)。如果我将其设置为弱,则以编程方式分配 UITableView 似乎不起作用。然而,如果我让它变得强大,那么如果使用 xib,它不一定会正确释放。处理此案的最佳方法是什么?

最佳答案

当作者知道其他人保留了该对象时,属性通常被声明为弱。一个很好的例子是 View Controller 想要保留指向其主视图的 subview 的指针。主视图的 subview 集合是一个数组,该数组保留其元素( subview 依此类推)。

因此,将 TableView 声明为弱是正确的,无论它是否是通过 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;
}
}

关于objective-c - 强 vs 弱 - 如何定义可能连接或不连接到 IBOutlet 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com