[IOS] Separates DataSource and builds lighter Uiviewcontroller

Source: Internet
Author: User

See an article in Objccn.io to build a lighter view Controllers, and practice it to deepen your understanding.



Xinjiang project, Learn--tableview, class prefix for LT, began our experiment.


First, you need to drag a uitableview in the storyboard, declare the TableView variable in the header file and establish the connection:





New Arraydatasource class, as the DataSource of TableView. The goal is to separate the datasource from the original Viewcontroller:

  arraydatasource.h//  Objc.io Example Project (issue #1)//#import <foundation/foundation.h>typedef void (^tableviewcellconfigureblock) (ID cell, ID item); @interface Arraydatasource:nsobject <uitableviewdatasource >-(ID) Initwithitems: (Nsarray *) Anitems     cellidentifier: (NSString *) Acellidentifier Configurecellblock: ( Tableviewcellconfigureblock) aconfigurecellblock;-(ID) Itematindexpath: (Nsindexpath *) Indexpath; @end

arraydatasource.h//Objc.io Example Project (issue #1)//#import "ArrayDataSource.h" @interface Arraydatasource () @p Roperty (nonatomic, Strong) Nsarray *items, @property (nonatomic, copy) NSString *cellidentifier; @property (Nonatomic, copy) Tableviewcellconfigureblock Configurecellblock; @end @implementation arraydatasource-(ID) init{return nil;} -(ID) Initwithitems: (Nsarray *) Anitems cellidentifier: (NSString *) Acellidentifier Configurecellblock: (    Tableviewcellconfigureblock) aconfigurecellblock{self = [super init];        if (self) {self.items = Anitems;        Self.cellidentifier = Acellidentifier;    Self.configurecellblock = [Aconfigurecellblock copy]; } return self;} -(ID) Itematindexpath: (Nsindexpath *) indexpath{return self.items[(Nsuinteger) indexpath.row];} #pragma mark uitableviewdatasource-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{return self.items.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{UITableViewCell *cell = [TableView DequeueReusableCellWithIdentifier:self.cellIdentifier Forindexp    Ath:indexpath];    ID item = [self Itematindexpath:indexpath];    Self.configurecellblock (cell, item); return cell;} @end

As you can see, this DataSource management class accepts three variables for initialization, namely:

1.anItems, the object that stores the tabular data, is a nsarray, which stores the encapsulated object, and we don't know what type it is, so we use the ID to take out the elements.

2.cellIdentifier, a cell identifier used to specify the cell used by the TableView, is the unique identifier of the cell, which can be specified when creating and designing the cell.

3.configureCellBlock, a block to set each cell, because the specific item format we do not know, so we do not know how to initialize a cell inside the data, we need to set the block, Because the purpose of this block is to apply the item's data to the cell, the block accepts two parameters, cell and item.


Next, add a Ltmycell class as a custom cell class. Add two labels to the xib to display the data:





Connect the two labels in the Xib with the. h header file, after which the header file is as follows:

+ (uinib *) nib, @property (weak, nonatomic) Iboutlet UILabel *phototitlelabel; @property (weak, nonatomic) Iboutlet UILabel *photodatelabel;


To modify the. m file, implement the following method:

+ (uinib *) nib{    return [uinib nibwithnibname:@ "Photocell" Bundle:nil];} -(void) sethighlighted: (BOOL) highlighted animated: (BOOL) animated{    [Super sethighlighted:highlighted animated: Animated];    if (highlighted) {        Self.photoTitleLabel.shadowColor = [Uicolor darkgraycolor];        Self.photoTitleLabel.shadowOffset = Cgsizemake (3, 3);    } else {        Self.photoTitleLabel.shadowColor = nil;    }}



Next, to create a new Ltphoto wrapper class, we need to split the data for presentation:

ltphoto.h//learn-tableview////Created on 8/11/14.//Copyright (c). All rights reserved.//#import <Foundation/Foundation.h> @interface ltphoto:nsobject <NSCoding> @property ( nonatomic, copy) nsstring* name; @property (nonatomic, strong) nsdate* CreationDate; @end////ltphoto.m//Learn-tableview Created on 8/11/14.//Copyright (c). All rights reserved.//#import "LTPhoto.h" static NSString * Const IDENTIFIERKEY = @ "identifier"; static NSString * Const NAM EKey = @ "name"; static NSString * Const CREATIONDATEKEY = @ "CreationDate"; static NSString * Const RATINGKEY = @ "rating"; @im    Plementation ltphoto-(void) Encodewithcoder: (nscoder*) coder{[coder EncodeObject:self.name Forkey:namekey]; [Coder EncodeObject:self.creationDate Forkey:creationdatekey];} -(BOOL) requiressecurecoding{return YES;    -(ID) Initwithcoder: (nscoder*) coder{self = [super init]; if (self) {self.name = [coder decodeobjectofclass:[nsstring class] foRkey:namekey];    Self.creationdate = [Coder Decodeobjectofclass:[nsdate class] forkey:creationdatekey]; } return self;} @end


After we have finished Ltphoto This package object, we can expand the category of the original MyCell. Create a new Category:



The specific code is as follows:

#import "LTMyCell.h" @class Ltphoto; @interface Ltmycell (Configureforphoto)-(void) Configureforphoto: (Ltphoto *) photo ; @end////  ltmycell+configureforphoto.m//  learn-tableview////  Created by what on 8/11/14.//  Copyright (c). All rights reserved.//#import "Ltmycell+configureforphoto.h" #import "LTPhoto.h" @implementation Ltmycell ( Configureforphoto)-(void) Configureforphoto: (Ltphoto *) photo{    self.photoTitleLabel.text = photo.name;    Self.photoDateLabel.text = [Self.dateformatter stringFromDate:photo.creationDate];} -(NSDateFormatter *) dateformatter{    static NSDateFormatter *dateformatter;    if (!dateformatter) {        dateformatter = [[NSDateFormatter alloc] init];        Dateformatter.timestyle = Nsdateformattermediumstyle;        Dateformatter.datestyle = Nsdateformattermediumstyle;    }    return dateformatter;} @end




The next step is to specify the datasource of TableView in Viewcontroller. Modify the M file code as follows:


ltviewcontroller.m//learn-tableview////Created on 8/11/14.//Copyright (c). All rights reserved.//#import "LTViewController.h" #import "ArrayDataSource.h" #import "LTMyCell.h" #import "ltmycell+ ConfigureForPhoto.h "#import" LTPhoto.h "static NSString * Const Photocellidentifier = @" Ltmycell "; @interface Ltviewcontroller () <UITableViewDelegate> @property (nonatomic, strong) Arraydatasource *photosarraydatasource; @end @implementation ltviewcontroller-(void) viewdidload{[Super viewdidload];//do no additional setup after loading T    He view, typically from a nib. [Self setuptableview];} -(void) setuptableview{Tableviewcellconfigureblock Configurecell = ^ (Ltmycell *cell, Ltphoto *photo) {[cel    L Configureforphoto:photo];        };    Nsmutablearray *photos = [[Nsmutablearray alloc] init];        for (int i = 0; i < i++) {Ltphoto *photo = [[Ltphoto alloc] init];        Photo.name = @ "Hello";    Photo.creationdate = [NSDate Date];    [Photos Addobject:photo];                                                         } Self.photosarraydatasource = [[Arraydatasource alloc] Initwithitems:photos Cellidentifier:photocellidentifier Configurecellbloc        K:configurecell];        _tableview.datasource = Self.photosarraydatasource;    [_tableview Registernib:[ltmycell nib] forcellreuseidentifier:photocellidentifier]; } #pragma mark uitableviewdelegate-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{NSLog (@ "click!");}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end

This achieves the basic datasource separation.


Project Source Address: Learn-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.