Don't turn Viewcontroller into a "trash bin" that handles TableView.

Source: Internet
Author: User

Please support the original, if you need to reprint, please specify the source @teason

Say in front:

Recently there is a MVVM very hot mode, I believe it is the advent of modular iOS development, in my opinion, it is still a MVC pattern, just a variant. Of course some people use the idea of responsive programming to subvert the routine, but today we focus our discussion on the design pattern of the code.

Instead of focusing on explaining the origins of MVVM, let's look at how a typical IOS is built and know from there MVVM :


Typical Model-view-controller Setup


What we see is a typical MVC setup. Modelrenders the data, View renders the user interface, and View Controller adjusts the interaction between it.
Think about it a little bit, although View 和 View Controller technically different components, but they are almost always hand in hand together, in pairs. When did you see a View pair that could be paired with different View Controller ? Or vice versa? So, why not formalize their connections?


Intermediate


This is a more accurate description of the code you might have written MVC . But it does not do much to solve iOS the growing weight-level view controller in the application. In a typical MVC application, Many logic is put in View Controller . Some of them do belong View Controller , but more so-called "logic for Display", in MVVM terms of terminology--something that transforms Model data into View something that can be rendered, such as converting one NSDate to a formatted one NSString .
There is something missing in our diagram. Something that allows us to place all the representations of logic. We're going to call it “View Model” --it's in View/Controller Model between:


Model-view-viewmodel


It looks much better! This diagram accurately describes what is MVVM : an MVC enhanced version, we formally connect the view and the controller, and put the representation logic from the Controller move out into a new object, that is View Model . MVVMIt sounds complicated, but it's essentially a well-optimized MVC architecture that MVC you're already familiar with.

Well, the introduction is over, this is a cushion.
If you think the right method is all in place for ViewController future maintenance and expansion. You can be stubborn. Then click the "X" in the upper right corner of the browser ...


Screen shot 2015-12-14 pm 3.58.00.png

Of course, there are ViewController many aspects about slimming. Today, however, we talk about the Controller representation logic of separating tableview from the. Why is the introduction of the MVVM design pattern, is also elaborated this main idea is interlinked. is to move the logical part to the layer as far as possible. Model You can think of it as a middle layer, the so-called "logical part" can be a variety of delegate, network requests, caches, databases, coredata and so on, while the controller is used to organize the concatenation of them. Make the whole program go through.

Body

It's easy to think UITableViewDataSource UITableViewDelegate of extracting the code and putting it in a separate class.
But I find that there is something that can be abstracted out.
For example, cell the build, cell row height, click, and so on. I've also used the block form to make the function callback. If you don't know much about block, look here first.
In addition, if you also use the .xib build heavily Cell , that will fit well with the classes I encapsulate.
Remember that I used .xib the default name to define the cell's identifier. If you want to use it for combat, remember to set the cell's identifier in Xib.

XTTableDataDelegateof the Processing class.h

#import<Foundation/Foundation.h>#import<UIKit/UIKit.h>typedefvoid (^tableviewcellconfigureblock) (Nsindexpath *indexpath,ID Item, Xtrootcustomcell *cell);typedefCGFloat (^cellheightblock) (Nsindexpath *indexpath,ID item);typedefvoid (^didselectcellblock) (Nsindexpath *indexpath,ID item);@interfacexttabledatadelegate: nsobject < Uitableviewdelegate,uitableviewdatasource>//1-(id) Initwithitems: (nsarray *) Anitems cellidentifier: (nsstring *) acellidentifier Configurecellblock: (tableviewcellconfigureblock) AConfigureCellBlock Cellheightblock: (cellheightblock) Aheightblock Didselectblock: (didselectcellblock) didselectblock; //2-(void) Handletableviewdatasourceanddelegate: ( uitableview *) Table; //3-(id) Itematindexpath: ( Nsindexpath *) Indexpath;  @end             

Note://1. Initialization method: Data source, Cellidentifier, three blocks respectively corresponding configuration, row high, click.
2. Will UITableViewDataSource and be UITableViewDelegate located inXTTableDataDelegate
3. The default indexPath.row corresponds to each dataSource . Corresponding returnitem

In addition, in order to be more thorough, it is necessary to abstract the "root Cell ". But this is not conducive cell to expansion. In order to avoid model and view coupling. So use category to do the extension of the class.

 #import  <uikit/uikit.h> @interface  UITableViewCell (extension) + (void) registertable: (uitableview *) Table Nibidentifier: (nsstring *) identifier;-(void) Configure: (uitableviewcell *) cell customobj: (id) obj Indexpath: (nsindexpath *) Indexpath; + ( cgfloat) Getcellheightwithcustomobj: (id) obj IndexPath: ( Span class= "hljs-built_in" >nsindexpath *) Indexpath;  @end             

Therefore UITableViewCell+Extension , the new cell is implemented through the extension of the class.
Note://1. Not explained.
2. Configure and draw a cell subclass from a data source be sure to override this method
3. Calculates the height subclass of a cell based on the data source to override the method, if not written as the default value of 44.0

#pragma mark-public+ (void) Registertable: (UITableView *) Table Nibidentifier: (NSString *) identifier{[table registernib:[Self nibwithidentifier:identifier] forcellreuseidentifier:identifier];}#pragma mark-- #pragma mark-rewrite these func in subclass-(void) Configure: (uitableviewcell *) cell customobj: (id) obj Indexpath: (nsindexpath *) indexpath{//Rewrite this func in Subclass!} + (cgfloat) Getcellheightwithcustomobj: (id) obj IndexPath: ( nsindexpath *) indexpath{//Rewrite this func in subclass if Necessary if (!obj) {return 0.0f; Span class= "hljs-comment" >//if obj is null. } return 44.0f; //Default cell height}           

So the new cell class is implemented as follows: implementing two new methods

- (void) Configure: (UITableViewCell *) cell customobj: (ID) obj Indexpath: (Nsindexpath *) indexpath{MyObj *myobj = (MYOBJ *) obj;    MyCell *mycell = (MyCell *) cell; MyCell.lbtitle.text = Myobj.name; Mycell.lbheight.text = [ NSString stringwithformat:@ "My Height is:%@" @ (myobj.height )] ; Cell.backgroundcolor = Indexpath.row% 2? [uicolor Greencolor]: [uicolor Browncolor];} + (cgfloat) Getcellheightwithcustomobj: (id) obj IndexPath: ( nsindexpath *) indexpath{return ((MYOBJ *) obj) .height;}              

Look at the results, thin behind the controller clean not like the strength, only left the method. hehe.

- (void) setuptableview{Self. Table. Separatorstyle =0; Tableviewcellconfigureblock Configurecell = ^ (Nsindexpath *indexpath, MyObj *obj, Xtrootcustomcell *cell) {[cell Configure:cell customobj:obj Indexpath:indexpath];} ; Cellheightblock Heightblock = ^CGFloat (Nsindexpath *indexpath,id Item) {return [MyCell Getcellheightwithcustomobj:item indexpath:indexpath];}; Didselectcellblock Selectedblock = ^ (nsindexpath *indexpath, id Item) {nslog (@ "click Row:%@" @ (Indexpath .row)) ; } ; self.tablehander = [[Xttabledatadelegate alloc] Initwithitems:self.list cellidentifier:mycellidentifier Configurecellblock:configurecell Cellheightblock:heightblock Didselectblock:selectedblock]; [self.tablehander handletableviewdatasourceanddelegate:< Span class= "Hljs-keyword" >self.table];}        

Many .m files are too lengthy, I do not post to the blog, the main blog is to talk about ideas, thinking is kingly.
Of course, if you want to understand, you can look at the source code, I uploaded github , point I download, like to add a??, to the open source is a great encouragement.
Any questions or suggestions, welcome, I will read your message.

Introducing MVVM
Lighter View Controllers
Table View Programming Guide
Cocoa Core Competencies:controller Object

    recommended Expand Reading

    Don't turn Viewcontroller into a "trash bin" that handles TableView.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.