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

在翻看代码的时候,因为使用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]));
    }
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值