简体   繁体   中英

Should I store data in my custom UITableView?

I have 2 viewControllers that each contains one UITableView among other subviews. The 2 UITableViews have the same section structure and cell types, but the data source is different.

So I decided to extract this UITableView into a custom UITableView. The custom UITableView implements methods like tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath , and is its own data source and delegate. The viewController only provides data.

The question is I can't figure out which is the best way for viewControllers to provide data. I can think of 2 ways:

first way

in MyCustomTableView.h:

@protocol MyCustomTableViewDataProvider <NSObject>
- (NSArray*)dataArray;
@end

@interface MyCustomTableView : UITableView
@property (nonatomic, weak) id<MyCustomTableViewDataProvider> dataProvider;
@end

The viewController should implement this protocol:

- (NSArray*)dataArray {
    return self.dataArray;
}

And in MyCustomTableView.m I use it like:

NSArray* dataArray = [self.dataProvider dataArray];

second way

in MyCustomTableView.h:

@interface MyCustomTableView : UITableView
@property (nonatomic, weak) NSArray* dataArray;
@end

Every time when there's a change in data, the viewController should inform the custom TableView to update its data:

self.customTableView.dataArray = self.dataArray;

And in MyCustomTableView.m I use it like:

self.dataArray

It seems that the second way could save some code, but I heard that you shouldn't store data in views because it violates the MVC principle. Could you please give me some advice? Many thanks!

IMHO, I wouldn't subclass any UIView unless it's absolutely necessary. Both TableViews and Collections provide protocols to control their behavior correctly.

If I were you, in order to keep the ViewController clean and short, I would create a custom NSObject implementing both UITableViewDelegate and DataSource protocols. This class would be in charge of providing the style of cells and sections (that is shared in those 2 table views) and also the data source. Of course, this object must have a property referencing its TableView.

The ViewController would only be in charge of triggering data retrieval whenever is needed. That data should be passed to that custom NSObject, which would be in charge of updating the table view.

BTW, this object could even be added through InterfaceBuilder.

It's a bit old, I know, but you could check : Lighter VC It's just a step forward towards MVVM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM