UiTableView 使用技巧1 (datamodel与datasource独立)

Qt表格之Model/View实现 Qt Model/View 阅读详情

在翻看代码的时候,因为使用UITableView的原因.导致代码很长.虽然有函数定位功能.不过datasource与datamodel经常糅合在controller里面.感觉很不清爽.修改起来也麻烦.在学习苹果官方自带文档以后.做了如下修改.先看示例.后发代码



以上的代码viewcontroller中,完全隐藏了datamodel与datasouce的实现.使得viewcontroller的逻辑看起来很条理很清晰.

而且隐藏以后.datamodel与datasource互相独立.保持接口一致.这样datamodel可以随意修改数据的来源.datasource可以随意修改cell的显示.而controller只需要负责协调各部分view的关系即可.



下面是代码:

//
//  main.m
//  ControlDemo
//
//  Created by watsy0007 on 12-6-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>


#define BARBUTTONITEM(title,act) [[[UIBarButtonItem alloc] initWithTitle:title \
style:UIBarButtonItemStylePlain \
target:self \
action:act] autorelease];

//--------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark tableDataModel()

@interface tableDataModel : NSObject {
    NSDictionary *_dataDictionary_;
}

- (NSInteger) numberOfSections;
- (NSArray *) sections;

- (NSInteger) numberOfRowAtSection:(NSInteger) nSection;
- (NSArray *) rowAtSection:(NSInteger) nSection;

@end

@implementation tableDataModel

- (id) init {
    if (self = [super init]) {
        _dataDictionary_ = [[NSDictionary alloc] initWithObjectsAndKeys:
                            
                            [NSArray arrayWithObjects:
                             
                             [NSDictionary dictionaryWithObjectsAndKeys:@"管理员1",@"title",@"超级管理员",@"subtitle", nil],
                             [NSDictionary dictionaryWithObjectsAndKeys:@"管理员2",@"title",@"普通管理员",@"subtitle", nil]
                             
                             , nil],@"管理员",
                            
                            [NSArray arrayWithObjects:
                             
                             [NSDictionary dictionaryWithObjectsAndKeys:@"用户1",@"title",@"小王",@"subtitle", nil]
                             ,
                             [NSDictionary dictionaryWithObjectsAndKeys:@"用户2",@"title",@"小张",@"subtitle", nil]
                             
                             , nil],@"用户",
                            
                            nil];
    }
    return self;
}

- (void) dealloc {
    [_dataDictionary_ release];
    
    [super dealloc];
}

- (NSInteger) numberOfSections {
    return [[_dataDictionary_ allKeys] count];
}
- (NSArray *) sections {
    return [_dataDictionary_ allKeys];
}

- (NSInteger) numberOfRowAtSection:(NSInteger) nSection {
    if (nSection < [self numberOfSections]) {
        NSString *sKey = [[self sections] objectAtIndex:nSection];
        return [[_dataDictionary_ objectForKey:sKey] count];
    }
    
    return 0;
}
- (NSArray *) rowAtSection:(NSInteger) nSection {
    if (nSection < [self numberOfSections]) {
        NSString *sKey = [[self sections] objectAtIndex:nSection];
        return [_dataDictionary_ objectForKey:sKey];
    }
    
    return nil;
}

@end

//--------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark tableDatasource()

@interface tableDataSource : NSObject <UITableViewDataSource>

@property (nonatomic, assign) tableDataModel *dModel;
@end

@implementation tableDataSource

@synthesize dModel = _dModel;

#pragma mark -
#pragma mark table view datasource delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_dModel numberOfSections];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dModel numberOfRowAtSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *strCell = @"demoCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
    if (!cell) {
        //UITableViewCellStyleDefault
        //UITableViewCellStyleSubtitle
        //UITableViewCellStyleValue1
        //UITableViewCellStyleValue2
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2
                                      reuseIdentifier:strCell];
    }
    
    NSDictionary *dict = [[_dModel rowAtSection:[indexPath section]] objectAtIndex:[indexPath row]];
    
    
    cell.textLabel.text = [dict objectForKey:@"title"];
    cell.detailTextLabel.text = [dict objectForKey:@"subtitle"];
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"标题:%@",[[_dModel sections] objectAtIndex:section]];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"标题:%@",[[_dModel sections] objectAtIndex:section]];
}

@end

//--------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark ViewController()

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> {
    UITableView *_tableView_;
    tableDataModel  *_dModel;
    tableDataSource     *_dSource;
}
@end

@implementation ViewController

- (void) dealloc {
    [_dSource release];
    [_dModel release];
    [_tableView_ release];
    [super dealloc];
}
- (void) viewDidLoad {
    [super viewDidLoad];
    self.title = @"UITableView demo";
    
    [[self view] setBackgroundColor:[UIColor whiteColor]];
    
    _tableView_ = [[UITableView alloc] initWithFrame:self.view.bounds
                                               style:UITableViewStyleGrouped];
    
    //自动适应高度
    _tableView_.autoresizingMask = UIViewAutoresizingFlexibleTopMargin |
    UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tableView_];
    
    _dModel = [[tableDataModel alloc] init];
    _dSource = [[tableDataSource alloc] init];
    _dSource.dModel = _dModel;
    _tableView_.dataSource = _dSource;
    _tableView_.delegate = self;
}

- (void) viewDidUnload {
    [_dSource release];
    [_dModel release];
    [_tableView_ release];
    [super viewDidUnload];
}
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return YES;
}
@end


//-----------------------------------------------------------------------------------------------------

#pragma mark -
#pragma mark AppDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIViewController *viewController;

@end

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (void) dealloc {
    [_window release];
    [_viewController release];
    
    [super dealloc];
}

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    srand(time(NULL));
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    self.viewController = [[ViewController alloc] init];
    
    UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:self.viewController]; 
    self.window.rootViewController = controller;
    [controller release];
    
    [self.window makeKeyAndVisible];
    return YES;
}

@end

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}


python3+PyQt5 使用数据库窗口视图 能够为数据库数据提供的最简单的用户界面之一就是窗体,窗体可以一次性呈现出来自同一记录的各个域。本文通过python3+pyqt5改写实现了python Qt gui 快速变成15章的例子。 阅读详情

相关推荐

基于Docker的D435i相机与IMU联合标定实战指南

本文详细介绍了基于Docker的D435i相机与IMU联合标定实战指南,涵盖kalibr镜像构建、IMU标定全流程、双目相机标定技巧及联合标定结果验证。通过Docker容器化部署,简化了复杂依赖环境,提升标定效率与精度,适用于机器人视觉与SLAM应用。

weixin_30872337的博客 241

iOS-将UITableViewDataSource协议和其他协议分离开

原文链接:点击打开链接

梦想实现家Dyh 867

Android开发者必看:5分钟搞定MQTT客户端连接EMQX服务器(附完整代码)

本文为Android开发者提供了一份快速实现MQTT客户端连接EMQX服务器的实战指南。通过引入Eclipse Paho SDK,详细讲解了从项目配置、权限申请到核心连接、主题订阅与消息发布的完整流程,并附有即拿即用的Kotlin代码,帮助开发者在物联网应用中高效集成轻量级实时通信功能。

weixin_29228781的博客 272

如何将UITableViewDelegate和UITableViewDataSource从UITableViewController中分离出来?

      大家都知道如果给UITableViewController装载一些数据和控制cell的行为(高度,样式等)都需要指定UITableView的delegate给自身,一般会使用IB或者在viewDidLoad中写上self.tableView.delegate = self;然后实现UITableViewDelegate和UITableViewDataSource中的方法,例如:– tableView:cellForRowAtIndexPath: 等等.      那么如何将实现UITableVi

JAVA 1万+

Linux内核模块开发实战指南(2025版)

2025年Linux内核模块开发迎来革命性突破!本文将从零开始手把手教你构建可动态加载的AI加速驱动模块,揭秘最新内核特性与开发技巧,更包含独家性能调优方案与跨架构移植秘籍。文末附赠价值百万的调试脚本,助你轻松突破开发瓶颈!

资深全栈架构师,乐于在 优快云 分享技术见解,与大家携手共进,共攀技术巅峰! 1811

利用Civil3D装配设计器(SAC)建设高度形状自适应挡土墙

之前的模型都是点线,最后加一个形状,形成面。再根据现场测得的挡土墙的墙脚的点生成中心线(alignment),在中心线的基础上生成在现有地面(existing ground level)的高程(profile)。简单的说,该墙的墙趾啊,墙踵啊,基底下面那个把儿啊,都是随着高度变化的,而高度是随着下面这个高程图变化的。接着出现角度和Y的文本框,角度92,y 值随便写一个,然后重要的是,高程目标选路面(优先于Y值)。意思是P2的高度,也就是路面的高程,减去P10,墙脚高程,再减去墙脚埋进地里的深度0.8m。

测量老覃 的博客 1132

iOS Controller 瘦身运动之 UItableView datasource 与 delegate的分离

iOS Controller 瘦身运动之 UItableView datasource 与 delegate的分离         最近在公司进行了代码的一些优化,所以在空闲之余,把相关的经验总结出来:      前提:       优化的时候,我首先就把矛头对象了UITableView,我是做电商的,基本上每个页面都用到了UITableView. 而UITableView

zhonggaorong的专栏 2959

Android 开发实战:从零到一集成 espeak-ng 实现中文离线 TTS(无需账号开箱即用)

本文详细介绍了如何在 Android 项目中集成 espeak-ng,实现中文离线语音播报。通过下载 so 库、编写 Java 接口、封装管理类,开发者可快速构建无需账号的 TTS 功能。文章覆盖从零到一的开发步骤、调试技巧及性能优化,适合中高级 Android 开发者参考。

全栈 3320

零插件依赖:用Houdini Solaris LOPs原生跑通USD覆盖导出

交付时审片发现,镜头层里房子那组变换全部回弹了——之前那份全量导出把原始层覆盖了。这就是 Houdini Solaris USD 覆盖导出工作流要解决的问题:只记增量,不动原始层。 ## 先对齐两个术语,避免各说各话 本文"原生"指随 Houdini 自带的 LOP(Lighting Operator)模块,与旧版 USD Houdini 插件无关——仓库里已明确后者弃用([third_par

gitblog_01088的博客 368

FAST-LIVO2 源码精读(十六):接入自定义传感器——多雷达适配与内外参标定

本文是「FAST-LIVO2 激光-惯性-视觉里程计源码精读」专栏第十六篇。上一篇拆解了中每个关键参数的物理含义与调参路径,并反复强调外参RclPcl与时间偏移配错即全局失效;本篇承接这一悬念,回答更前置的工程问题——如何把 FAST-LIVO2 接到一套全新硬件上:新雷达如何通过的类型分支适配、相机内参与畸变模型如何配置、两组外参与时间偏移如何标定出来并填入 YAML,最后给出一份落地检查清单。

PX4-SLAM-PNC 200

基于深度学习的推荐系统设计与实现

基于深度学习的推荐系统设计与实现 作者:禅与计算机程序设计艺术 / Zen and the Art of Computer Programming / TextGenWebUILLM 基于深度学习的推荐系统设计与实现 关键词:深度学习, 推荐系统, 用

AI天才研究院 1079

UiTableViewdatasource的分离

创建ArrayDataSource类,继承于NSObject: ArrayDataSource.h中: #import &lt;UIKit/UIKit.h&gt; NS_ASSUME_NONNULL_BEGIN typedef void(^TableViewCellConfigureBlock)(id cell ,id item); @interface ArrayDataSource :...

九天揽月 896

【Prometheus】prometheus结合cAdvisor监控docker容器运行状态,并且实现实时告警通知

Docker的监控,可以使用Docker自带的stats命令来获取当前主机上运行中的容器的资源使用情况。 例如:容器的CPU使用率、内存占用、网络IO以及磁盘IO等指标。

景天科技苑 6万+

SpringBoot之数据访问操作

SpringBoot连接池DataSource定义Boot提供了默认内置集成的DataSource,也可以使用外部的。 1.spring.datasource默认连接池 默认内集成DataSource对象(默认,id名dataSource)开发只需要添加下面连接池jar包引入,Boot可以自动创建出DataSource连接池对象。<!-- tomcat连接池和jdbc支持 --> <dependen

zxh997234531的博客 1987

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

PyQt_完美安装pyqt5

https://blog.youkuaiyun.com/viatorsun/article/details/80369520

wjg1314521的博客 1万+

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

分离tableview的datasource , 实现ViewController “瘦身”

分离tableview的datasource ,  实现ViewController “瘦身” 这是一个实现轻量级ViewController的基本方法,大家通过这个代码页可以实现代理的分离. #import typedef void(^TableViewCellConfigureBlock) (id cell,id item); @inte

iOS随笔 1930

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

iOS 中NSArray NSSet转换 过滤重复与排序操作

很久没写ios代码。最近和朋友聊天时候有强迫症,想强烈把代码给优化。 问题是这样的:现在数据是日期数组,想过滤掉重复的日期,怎么解决。 原始代码 这里想到更简洁点。用NSSet来搞定。 NSArray *arr = @[@"12-11", @"12-11", @"12-11", @"12-12", @"12-13", @"12-14"]; NSSet *set = [NSSet s

watsy 2万+

ios 新版本 facebook SDK 分享方法

管理的例子挺好的。 官方的登录文档地址https://developers.facebook.com/ios/login-ui-control/ 使用方法 第一步添加appid 在info.plist中添加FacebookAppID 第二步添加loginview。facebook已经为用户做好了登录的方法 facebook的登录有3种 1:ios6以上自带的登录 2:fac

watsy 1万+

client 提交post 到 django出现403错误

当采用客户端象django的服务器提交post请求时。会得到403,权限异常。 因为django针对提交的请教,有校验。所以会如此。 解决办法http://stackoverflow.com/questions/6800894/django-returns-403-error-when-sending-a-post-request 导入模块 from django.view

watsy 1万+

iOS 5 新增的UIPageViewController 简单示例

代码说起来也不简单,不过也不复杂,类是UITableView 通过datasource与delegate委托获取数据源和操作. 下面直接上代码: CWPageModel.h #import @class CWPageController; @interface CWPageModel : NSObject @property (strong, nonatomic) NSAr

watsy 1万+

iOS下使用restkit测试restful架构下的数据交互

这里mark下,忙完手里的测试以后写上restful的示例。下面直接说ios下如何使用。 这篇文章写的比较精简。目前只写了get方法。post delete,put 部分下次在补上。 准备工作 首先需要知道restful走的是json协议的数据。为了测试,需要利用服务器返回一段json。大家可以选用熟悉的方法返回。 这里说一个比较简单的学习测试方法。 mac下面开启web

watsy 9553

unity3d 与 iOS 的交互

unity3d 通过 编辑器实现代码。资源的整合以后。 编译成ios时候,会把脚本部分翻译成arm指令。资源部分整合进去。 然后通过ios的OPENGL代码实现。 大致看一下ios的代码。unity3d从新实现了arm到C的过程。脚本代码从内存中重定向执行。 但是既然是ios本地执行。调用到ios的window和view。就可以绑定ios代码和界面。 iOS 导出

watsy 6893

UIResponder inputView与inputAccessoryView

看完以后觉得使用还是很方便的. 同时代码中还有UITextField的leftView与rightView示例. 代码: // // main.m // ControlDemo // // Created by watsy0007 on 12-6-3. // Copyright (c) 2012年 __MyCompanyName__. All righ

watsy 5945

UITextField 实现下拉显示自动补全列表

在别人的代码基础上自己又修改了1部分,增加了删除功能.自动调整高度功能.还有部分没完善的地方,使用时候自己可以适当调整. 先看实现效果. 类代码: // // AutocompletionTableView.h // // Created by Gushin Arseniy on 11.03.12. // Copyright (c) 2012 Arseniy Gus

watsy 5925

xpath 使用方法 演示

翻译文章,翻译的不是很好,请见谅 原文地址:http://manual.calibre-ebook.com/xpath.html In this tutorial, you will be given a gentle introduction to XPath, a query language that can be used to select arbitrary parts

watsy 5493
上一篇: 1天学习1个类库 UILocalNotification 示例
下一篇: UIResponder inputView与inputAccessoryView
watsy
博客等级 码龄19年 133粉丝 104原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值