use*_*464 2 objective-c uitableview xib
我正在编写一个可重用的类,它具有UITableView属性作为IBOutlet.但是,我希望该类创建一个UITableView,如果它没有连接到xib,因此是nil.如果我将它设置为弱,那么以编程方式分配UITableView似乎不起作用.但是,如果我强大,那么如果使用xib,它将不一定正确解除分配.处理这种情况的最佳方法是什么?
当作者理解其他人保留该对象时,通常会将属性声明为弱.一个很好的例子是一个视图控制器,它想要保持指向其主视图的子视图的指针.主视图的子视图集合是一个数组,并且数组保留其元素(对于子子视图,依此类推).
因此,无论是否通过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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |