UITableView setDataSource – Disallowed Object Error

综合技术 2017-11-15

I have a UIViewController
which contains this property:

@property (weak, nonatomic) IBOutlet UITableView *customerTableView;

In the UIViewController's viewDidLoad
method, I have the following:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // ...
    CustomerTableViewDataSource *dataSource = [[CustomerTableViewDataSource alloc]
        init];
    [dataSource setData:customersSource];
    [customerTableView setDataSource:dataSource];
}

I receive this with NSZombies enabled:

*** -[CustomerTableViewDataSource numberOfSectionsInTableView:]: message sent to
deallocated instance 0x3e07a0

The deallocated instance address is the same as the data source.

Is there any reason why the data source isn't 'sticking'?

Using the simulator and Zombies, I see that the reference is being released in viewDidLoad
, which I suppose is no surprise since I declared it in that method and it should fall out of scope, however I would think that calling setDatasource
would increase the refct. Well, it apparently doesn't.

Is there any way I can change this behavior?

Note: Everything works
if I create an ivar and store the data source, but I feel like that clutters my class. Is this just life in the city?

From the documentation
of UITableView
:

@property(nonatomic, assign) id dataSource

Discussion

The data source must adopt the UITableViewDataSource protocol. The data source is not retained.

This means that customerTableView
expects you to retain your data source object, which you did not do. Same goes for UITableView
's delegate (in fact, for almost any delegate in cocoa, except CALayer
's one). This design decision is made for a reason: the object that holds on to UITableView
very often also serves as its delegate. Had the delegate been retained, the programmers would have to deal with retain cycles.

Unfortunately, the consequence of that decision is the problem that you are having: now you need to retain the data source (and the delegate, if any), e.g. by setting up an ivar.

您可能感兴趣的

如何处理一个tableView中同种model多种cell相同逻辑的情况?... 这是购物车页面: 有4种cell: 1.一般商品cell 2.带赠品的商品cell 3.满赠商品cell 4.补货中商品cell 一般来说,有多少种cell就要自定义多少种cell,但是这4种cell又有相同的逻辑处理,如点击商品图片进入商品详情页。如何处理既不会让...
IOS UITableview delete line with animation I saw a lot of questions about it but didn't found a solution to my problem. I have a tableview with custom cell. In each cell I have a timer. When ...
iOS开发之tableView cell的展开收回功能实现... 一、实现方法例如好友分组,分为好友和陌生人两组,实现点击好友和陌生人展开或收回该分组对应的cell的功能。 实现:可以分组对应tableView的section,点击section展开和收回cell。 创建一个临时数组selectedArr存储需要展开的section。点...
The complete animation notification after UITableV... UITableView has that built-in animation in which after a cell is reordered, it lays gently into the vacant space. Is there a where to tap into some s...
iOS开发中一些”有挑战”的问题 本文源自这里, 另外还有姊妹篇 iOS开发中一些"有趣"的问题 目录 问题1: navigation push时隐藏的Tarbar怎么又回来了 问题2: 莫名消失的MBProgressHUD 问题3: 奇怪的DAContextMenuTableVi...