·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 【读书笔记】iOS-简单的数据驱动程序

【读书笔记】iOS-简单的数据驱动程序

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

一,效果图。

 

 

二,,工程文件如下图所示:

 

 

三,DataModel.h

复制代码

#import <Foundation/Foundation.h>

 

@interface DataModel : NSObject

{

    NSArray *myData;

}

-(NSString *)getNameAtIndex:(int)index;

-(int)getRowCount;

 

@end

 

 

复制代码

 

 DataModel.m

复制代码

//数据库文件

#import "DataModel.h"

 

@implementation DataModel

 

-(id)init

{

    if (self=[super init]) {

        

        myData=[[NSArray alloc]initWithObjects:@"first",@"second",@"three",@"four", nil];

     }

    return self;

}

//显示数组中数据

-(NSString *)getNameAtIndex:(int)index

{

    return (NSString *)[myData objectAtIndex:index];

}

//显示行数

-(int)getRowCount

{

    return (int)[myData count];

}

@end

 

复制代码

 

四,ViewController.h

复制代码

#import <UIKit/UIKit.h>

#import "DataModel.h"

 

@interface ViewController : UIViewController

<UITableViewDataSource,UITableViewDelegate>

{

    UITableView *myTableView;

    DataModel *model;

}

@end

 

复制代码

ViewController.m

复制代码

#import "ViewController.h"

 

@interface ViewController ()

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    //初始化数据

    [self initData];

    //初始化界面

    [self addBackgroundView];

}

#PRagma -mark -functions

//初始化数据

-(void)initData

{

     model=[[DataModel alloc]init];

}

//初始化界面

-(void)addBackgroundView

{

    myTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 100, 320, 300)];

    myTableView.dataSource=self;

    myTableView.delegate=self;

    [self.view addSubview:myTableView];

 

}

#pragma -mark -UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [model getRowCount];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 40;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier=@"Cell";

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell==nil) {

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    cell.textLabel.text=[NSString stringWithFormat:@"%@",[model getNameAtIndex:(int)indexPath.row]];

    return cell;

    

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

复制代码

参考资料:《iOS数据库应用高级编程(第2版)》