iOS 更轻量级的控制器 数据请求和解析的封装

来源:互联网 发布:格式化js代码 编辑:程序博客网 时间:2024/06/03 18:08

很多刚入行的朋友可能对如何写出更轻量级的控制器比较迷茫,直接上代码,封装数据请求和解析,然后以代理的形式返回,有用拿走,不喜勿喷!

控制器代码
TopRankingController.h

#import <UIKit/UIKit.h>@interface TopRankingController : UIViewController@end

TopRankingController.m

#import "TopRankingController.h"#import "TopRankingDataGet.h"@interface TopRankingController ()<UITableViewDelegate, UITableViewDataSource, topRankingDataGet>@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;@property (strong, nonatomic) IBOutlet UITableView *tableView1;@property (strong, nonatomic) IBOutlet UITableView *tableView2;@property (strong, nonatomic) IBOutlet UITableView *tableView3;@property (strong, nonatomic) NSMutableArray *modelArray1;@property (strong, nonatomic) NSMutableArray *modelArray2;@property (strong, nonatomic) NSMutableArray *modelArray3;@property (strong, nonatomic) IBOutlet UILabel *label1;@property (strong, nonatomic) IBOutlet UILabel *label2;@property (strong, nonatomic) IBOutlet UILabel *label3;@property (strong, nonatomic) IBOutlet UIView *view1;@property (strong, nonatomic) IBOutlet UIView *view2;#pragma mark - 一个数组 用来存放所有的排行方式@property (strong, nonatomic) NSArray *sortedTypeArray;@end@implementation TopRankingController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view from its nib.#pragma mark - 设置导航栏    [self setNav];#pragma mark - 注册cell    [self registerCell];#pragma mark - RAC 监控scrollerView偏移    [self addObserver];#pragma mark - 请求数据    [self getData];}- (void)setNav{    self.navigationController.navigationBar.translucent = NO;    self.navigationItem.title = @"热门排行";}- (void)registerCell{    [self.tableView1 registerNib:[UINib nibWithNibName:@"BigCell" bundle:nil] forCellReuseIdentifier:@"bigCell"];    [self.tableView2 registerNib:[UINib nibWithNibName:@"BigCell" bundle:nil] forCellReuseIdentifier:@"bigCell"];    [self.tableView3 registerNib:[UINib nibWithNibName:@"BigCell" bundle:nil] forCellReuseIdentifier:@"bigCell"];}#pragma mark - 来回动- (void)addObserver{    [RACObserve(self.scrollView, contentOffset) subscribeNext:^(id x) {        self.view1.x =  [UIScreen mainScreen].bounds.size.width / 12 + self.scrollView.contentOffset.x / 3;        self.view2.x = self.view1.x;    }];    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];    [self.label1 addGestureRecognizer:tap1];    [self.label2 addGestureRecognizer:tap2];    [self.label3 addGestureRecognizer:tap3];}- (void)tap:(UITapGestureRecognizer *)sender{    CGPoint point = self.scrollView.contentOffset;    point.x = (sender.view.tag / 10000 - 1) * [UIScreen mainScreen].bounds.size.width;    self.scrollView.contentOffset = point;}#pragma mark - 请求数据 解析数据- (void)getData{    self.sortedTypeArray = @[@"weekly", @"monthly", @"historical"];    for (int i = 0; i < self.sortedTypeArray.count; i++) {        TopRankingDataGet *topDataGet = [TopRankingDataGet getDataAndResolveDataWithSortedType:self.sortedTypeArray[i]];        topDataGet.delegete = self;    }}#pragma mark - 懒加载- (NSMutableArray *)modelArray1{    if (!_modelArray1) {        self.modelArray1 = [NSMutableArray array];    }    return _modelArray1;}- (NSMutableArray *)modelArray2{    if (!_modelArray2) {        self.modelArray2 = [NSMutableArray array];    }    return _modelArray2;}- (NSMutableArray *)modelArray3{    if (!_modelArray3) {        self.modelArray3 = [NSMutableArray array];    }    return _modelArray3;}#pragma mark - 实现topDataGet代理方法- (void)getArray:(NSMutableArray *)array andSortedType:(NSString *)sortedType{    if ([sortedType isEqualToString:self.sortedTypeArray[0]]) {        self.modelArray1 = array;        [self.tableView1 reloadData];    }    if ([sortedType isEqualToString:self.sortedTypeArray[1]]) {        self.modelArray2 = array;        [self.tableView2 reloadData];    }    if ([sortedType isEqualToString:self.sortedTypeArray[2]]) {        self.modelArray3 = array;        [self.tableView3 reloadData];    }}#pragma mark - tableView代理方法- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 220;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    if (tableView.tag == 100) {        return self.modelArray1.count;    }    if (tableView.tag == 101) {        return self.modelArray2.count;    }    if (tableView.tag == 102) {        return self.modelArray3.count;    }    return 0;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    if (tableView.tag == 100) {        AllModel *model = self.modelArray1[indexPath.row];        BigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bigCell"];        [cell setContentWithModel:model];        return cell;    }    if (tableView.tag == 101) {        AllModel *model = self.modelArray2[indexPath.row];        BigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bigCell"];        [cell setContentWithModel:model];        return cell;    }    if (tableView.tag == 102) {        AllModel *model = self.modelArray3[indexPath.row];        BigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bigCell"];        [cell setContentWithModel:model];        return cell;    }    return 0;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    AllModel *model = nil;    if (tableView.tag == 100) {        model = self.modelArray1[indexPath.row];    }    if (tableView.tag == 101) {        model = self.modelArray2[indexPath.row];    }    if (tableView.tag == 102) {        model = self.modelArray3[indexPath.row];    }    DailyDetailController *dailyVC = [[DailyDetailController alloc] init];    [self.navigationController pushViewController:dailyVC animated:YES];    dailyVC.model = model;    [self hiddenTabBar];}- (void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];    [self xianshiTabBar];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

封装的数据请求和解析类的代码
TopRankingDataGet.h

#import <Foundation/Foundation.h>@protocol topRankingDataGet <NSObject>#pragma mark - 返回所需要的三个数组 对应三种排行方式- (void)getArray:(NSMutableArray *)array andSortedType:(NSString *)sortedType;@end@interface TopRankingDataGet : NSObject#pragma mark - 一个字符串 用来接受传过来的排行方式@property (nonatomic, strong) NSString *sortedType;#pragma mark - 代理棒@property (nonatomic, assign) id<topRankingDataGet>delegete;#pragma mark - 传入一个排序方式 完成请求数据 和数据解析等工作+ (TopRankingDataGet *)getDataAndResolveDataWithSortedType:(NSString *)sortedType;@end

TopRankingDataGet.m

#import "TopRankingDataGet.h"#define kTopUrl @"http://baobab.wandoujia.com/api/v3/ranklist?num=10&strategy=%@&udid=10a24205c9414591be7ae7a1fe28a374968712ab&vc=69&vn=1.9.1&deviceModel=YQ601&first_channel=eyepetizer_wandoujia_market&last_channel=eyepetizer_wandoujia_market"@implementation TopRankingDataGet- (instancetype)initWithSortedType:(NSString *)sortedType{    self = [super init];    if (self) {        self.sortedType = sortedType;    }    return self;}+ (TopRankingDataGet *)getDataAndResolveDataWithSortedType:(NSString *)sortedType{    TopRankingDataGet *topDataGet = [[TopRankingDataGet alloc] initWithSortedType:sortedType];    [topDataGet getDataAndSolveData];    return topDataGet;}#pragma mark - 请求数据 解析数据- (void)getDataAndSolveData{    NSString *urlString = [[NSString stringWithFormat:kTopUrl, self.sortedType] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL *url = [NSURL URLWithString:urlString];    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        [self jiexi:data];    }];}- (void)jiexi:(NSData *)data{    if (data) {        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];        NSArray *array = dic[@"itemList"];        NSMutableArray *modelArray = [NSMutableArray array];        for (NSDictionary *dic in array) {            AllModel *model = [[AllModel alloc] initWithDictionary:dic[@"data"]];            [modelArray addObject:model];        }        if (_delegete && [_delegete respondsToSelector:@selector(getArray:andSortedType:)]) {            [_delegete getArray:modelArray andSortedType:self.sortedType];        }    }}@end

由于要实现三个TableView的滚动 而笔者又是用xib加载的控件 故而引入了ReactiveCocoa框架 当然这个框架的作用远远不止于此 笔者以后会持续更新关于ReactiveCocoa框架的使用 关于 xib 上 加载scrollerView可能会出现的问题 很多博客都有讲解 在这里就不作解释了
第一次写博客 想想 还有点小激动

0 0