ios - 如何在 Storyboard 的 UITableView 中显示来自 sqlite 的数据

标签 ios objective-c sqlite uitableview storyboard

<分区>

我创建了一个应用程序。 在我的应用程序中,我将 2 个数组存储在 sqlite 表数据库中,但我无法在 UItableView 中从 sqlite 显示。 我在谷歌中搜索但没有找到关于 sqlite Storyboard中显示数据的信息。!!! 请指导我如何在 tableview 中显示来自 sqlite DB 的数据。 这是我的代码:

#import "ViewController.h"
#define DataName @"DB.sqlite"

@implementation ViewController
{
    NSDictionary * dictionary;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *Name = [NSArray arrayWithObjects:@"Ribery",@"Ronaldo",@"Messi",@"Zannati",@"Totti", nil];
    NSArray *Team = [NSArray arrayWithObjects:@"byern",@"R.Madrid",@"Barcelona",@"Inter",@"Rome", nil];
    for (int i = 0; i < [Name count]; i++)
    {
        NSString * name = [Name objectAtIndex:i];
        NSString * team = [Team objectAtIndex:i];
        dictionary = [NSDictionary dictionaryWithObjectsAndKeys:name,@"Name",team,@"Team",nil];
        NSString *query = [NSString stringWithFormat:@"insert into tableFootball (Name,Team) values('%@','%@')",[dictionary objectForKey:@"Name"],[dictionary objectForKey:@"Team"]];
        [self executeQuery:query];
    }

}
-(NSString *) dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"PATH %@",[documentsDirectory stringByAppendingPathComponent:DataName]);
    return [documentsDirectory stringByAppendingPathComponent:DataName];
}
-(void)executeQuery:(NSString *)query
{
    //NSLog(@"QUERY : %@",query);

    sqlite3_stmt *statement;
    if(sqlite3_open([[self dataFilePath] UTF8String], &DataBase) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(DataBase, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) != SQLITE_DONE)
            {
                sqlite3_finalize(statement);
            }
        }
        else
        {
            NSLog(@"query Statement Not Compiled");
        }

        sqlite3_finalize(statement);
        sqlite3_close(DataBase);
    }
    else
    {
        NSLog(@"Data not Opened");
    }
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}
- (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];
    }
    //I dont know what put here for display from sqlite
    return cell;
}

最佳答案

创建一个方法来获取存储在 sqlite 中的所有玩家,比如 findAllPlayers 。创建一个 dataSourceArray,它将保存从上一个方法返回的玩家。为了便于使用,很容易形成模型自定义对象而不是字典。

//Player.h

@interface Player : NSObject

@property (nonatomic) NSUInteger playerID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *team;

一个实用程序 PlayerDatabase,它从 sqlite 插入和获取播放器实例。

//PlayerDatabase.h

@class Player;
@interface PlayersDatabase : NSObject

+ (PlayersDatabase*)database;
- (NSArray *)findAllPlayers;
- (BOOL)insertPlayer:(Player *)player;

//PlayerDatabase.m
@implementation PlayersDatabase

static PlayersDatabase *_database;

+ (PlayersDatabase*)database {
    if (_database == nil) {
        _database = [[PlayersDatabase alloc] init];
    }
    return _database;
}

- (id)init {
    if ((self = [super init])) {

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [self databasePath];
        if (![fileManager fileExistsAtPath:filePath]) {
            NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"Players"
                                                                 ofType:@"db"];
            [fileManager copyItemAtPath:sqLiteDb
                                 toPath:filePath
                                  error:NULL];
        }

    }
    return self;
}

- (NSString *)databasePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    return [documentsDirectory stringByAppendingPathComponent:@"Players.db"];
}

- (NSArray *)findAllPlayers
{
    NSMutableArray *players = [NSMutableArray array];
    FMDatabase *database = [FMDatabase databaseWithPath:[self databasePath]];
    [database open];

    FMResultSet *resultSet = [database executeQuery:@"SELECT * from Player ORDER BY Name"];

    while ([resultSet next]) {

        Player *player = [[Player alloc]init];

        player.playerID = [resultSet intForColumn:@"PlayerID"];
        player.name     = [resultSet stringForColumn:@"Name"];
        player.team     = [resultSet stringForColumn:@"Team"];

        [players addObject:player];

    }

    [database close];

    return players;
}

- (BOOL)insertPlayer:(Player *)player
{
     FMDatabase *db = [FMDatabase databaseWithPath:[self databasePath]];
     [db open];
     BOOL success =  [db executeUpdate:@"INSERT INTO Player (Name,Team) VALUES (?,?);",player.name,player.team, nil];
     [db close];
     return success;
}

现在在带有 tableView 的 viewController 中,首先填充 sqlite,然后重新加载 tableView

//YourViewController.h 
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *names = [NSArray arrayWithObjects:@"Ribery",@"Ronaldo",@"Messi",@"Zannati",@"Totti", nil];
    NSArray *teams = [NSArray arrayWithObjects:@"byern",@"R.Madrid",@"Barcelona",@"Inter",@"Rome", nil];
    for (int i = 0; i < [Name count]; i++)
    {
        Player *player = [[Player alloc]init];

        player.name = names[i];
        player.team = teams[i];

        [[PlayerDatabase database] insertPlayer:player];
    }

    self.players = [self findAllPlayers];
    [self.tableView reloadData];

}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.players count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    //Here the dataSource array is of dictionary objects
    Player *player = self.players[indexPath.row];
    cell.textLabel.text = player.name;
    cell.detailTextLabel.text = player.team;

    return cell;
}

我已经按照上述教程制作了一个示例项目,数据已预加载到 sqlite 中。所以你可能需要调整它以供你使用。

Source Code

关于ios - 如何在 Storyboard 的 UITableView 中显示来自 sqlite 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16337087/

相关文章:

objective-c - 在访问Objective C属性时可以具有参数吗?

ios - 隐藏和取消隐藏 SKSprite 节点

ios - 为什么我收到错误 "Expected Identifier or"(""

sqlite - 在 SQLite 上使用 MicroLite

database - SQLite 数据库作为文本文件?

ios - 在静态 tableView 的底部设置按钮

objective-c - 使导航 Controller 在 iOS 6 和 iOS 7 中工作相同

ios - 创建密码实例 Objective-C 并获取 block 大小

ios - 按比例调整 UIImage 的大小然后裁剪

c# - 如何在 SQLite 查询中使用带参数的 Like 运算符?