繁体   English   中英

如何将数据从SQlite显示到表视图到iPhone应用程序

[英]How to Display data from SQlite into Table views to iPhone app

我正在使用SQlite3在Xcode 4.3中处理一个iPhone项目,SQlite和Xcode之间的连接已经完成,现在我想将我的数据显示到一个表视图(三个视图)并且只读它! 所以我有主表视图,选择raw - > take to 2nd view并从DB中加载其他数据选择raw - >转到详细信息视图以显示长文本和图像!

任何帮助赞赏。

AppDelegate.h

#import "AppDelegate.h"

#import "MasterViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize navigationController = _navigationController;

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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"cities.sqlite"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if (success) {

        NSLog(@"we have the database");

    } else {

        NSLog(@"we have no database");

        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"cities.sqlite"];


        BOOL moved = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:nil];

        if (moved) {
            NSLog(@"database copied");
        }

    }


    MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil] autorelease];
    self.navigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

MasterViewController.h

#import <UIKit/UIKit.h>
#import <sqlite3.h> 


@class DetailViewController;

@interface MasterViewController : UITableViewController {
    NSMutableArray *cities;
}

@property (strong, nonatomic) DetailViewController *detailViewController;

@end

MasterViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    students = [[NSMutableArray alloc] init];
    countries = [[NSMutableArray alloc] init];

    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)] autorelease];
    self.navigationItem.rightBarButtonItem = addButton;


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"cities.sqlite"];


    sqlite3 *database;

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

        const char *sqlStatement = "select * from cities_info";

        sqlite3_stmt *compileStatement;

        if (sqlite3_prepare_v2(database, sqlStatement, -1, &compileStatement, NULL) == SQLITE_OK) {


            while (sqlite3_step(compileStatement) == SQLITE_ROW) {

                NSLog(@"one record");

                NSString *cityName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compileStatement, 1)];

                [cities addObject:cityName];

            }

            NSLog(@"cities: %@",cities);  

        }


    } else {


        NSLog(@"error in database");

    }
}

大段引用

我建议使用SQLite的轻量级包装器 - 请参阅https://github.com/JohnGoodstadt/EasySQLite

这将允许:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _personTable.rows.count;
}

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

     NSArray* row= _personTable.rows[indexPath.row];
     cell.textLabel.text = row[[_personTable colIndex:@"lastname"]];
     ...

通过使用表示SQL表的iVar来设置它:

self.personTable = [_db  ExecuteQuery:@"SELECT firstname , lastname , age , salary FROM person"];

并且数据库连接iVar传入您的SQL文件名:

self.db = [DBController sharedDatabaseController:@"DataTable.sqlite"];

首先,我建议使用FMDB ,它是围绕sqlite3的Objective-C包装器。 其次,我将创建一个带有共享实例的自定义数据访问对象,如下所示:

@interface MyDatabaseDAO : NSObject
    @property (nonatomic, strong) FMDatabase *database;
@end


@implementation MyDatabaseDAO
@synthesize database = _database;

+ (MyDatabaseDAO *)instance {
    static MyDatabaseDAO *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }

    return _instance;
}

- (id)init {
    self.database = [FMDatabase databaseWithPath:myDatabasePath];
    [self.database open];
}

- (void)dealloc {
    [self.database close];
}
@end

此DAO必须具有3种访问方法:一种用于数据库中的每个数据对象。 因为你不具体,我制作了这些没有任何特定属性的对象。

- (NSArray *)retrieveAllFirstViewItems {
    NSMutableArray *items = [NSMutableArray array];
    FMResultSet *resultSet = [FMDBDatabase.database executeQuery:@"SELECT * FROM myFirstViewItemTable"];    

    while ([resultSet next]) {
        // extract whatever data you want from the resultset
        NSString *name = [resultSet stringForColumn:@"name"]
        [items addObject:name];
    }
    [resultSet close];

    return items;
}

- (MySecondViewItem *)retrieveSecondViewItemFromIndexPath:(NSIndexPath *)indexPath {

    FMResultSet *resultSet = [FMDBDatabase.database executeQuery:@"SELECT * FROM mySecondViewItemTable WHERE pid = ?", [indexPath indexAtPosition:0]];
    if ([resultSet next]) {
        // extract whatever data you want from the resultset
        NSString *name = [resultSet stringForColumn:@"name"]
        MySecondViewItem *mySecondViewItem = [[MySecondViewItem alloc]
                initWithName:name withPID:[indexPath indexAtPosition:0]];
        [resultSet close];
        return mySecondViewItem;
    } else {
        return nil;
    }
}

- (MyThirdViewItem *)retrieveThirdViewItemFromIndexPath:(NSIndexPath *)indexPath {

    FMResultSet *resultSet = [FMDBDatabase.database executeQuery:@"SELECT * FROM mySecondViewItemTable WHERE pid = ?", [indexPath indexAtPosition:1]];
    if ([resultSet next]) {
        // extract whatever data you want from the resultset
        NSString *name = [resultSet stringForColumn:@"name"]
        MyThirdViewItem *myThirdViewItem = [[MyThirdViewItem alloc]
                initWithName:name withPID:[indexPath indexAtPosition:1]];
        [resultSet close];
        return myThirdViewItem;
    } else {
        return nil;
    }
}

由于它是只读的,因此这些都是必需的方法。 在你的第一个UITableView中,只需实现方法:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MySecondViewItem *mySecondViewItem = [[MyDatabaseDAO instance] retrieveSecondViewItemFromIndexPath:indexPath];
    //instantiate a view from this item and use [UINavigationController pushViewController:animated:] to navigate to it
}

剩下的只是以某种方式在视图中显示您的数据对象。 我建议在数据访问对象中尽可能多地进行数据检索,以便视图控制器可以读取数据对象的属性,而不必担心后端。

这里的所有都是它的! 我希望这有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM