7

我正在使用 SQlite3 在 Xcode 4.3 中开发一个 iPhone 项目,SQlite 和 Xcode 之间的连接已经完成,现在我想将我的数据显示到一个表格视图(三个视图)中并且它是只读的!所以我有主表视图,选择 raw --> 进入第二个视图并从 DB 加载其他数据 select 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;
}

主视图控制器.h

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


@class DetailViewController;

@interface MasterViewController : UITableViewController {
    NSMutableArray *cities;
}

@property (strong, nonatomic) DetailViewController *detailViewController;

@end

主视图控制器.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");

    }
}

块引用

4

2 回答 2

2

我建议在 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"];

以及传入您的 SQL 文件名的 DB Connection iVar:

self.db = [DBController sharedDatabaseController:@"DataTable.sqlite"];
于 2012-09-14T16:31:01.017 回答
0

首先,我建议使用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
}

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

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

于 2012-09-13T13:49:40.853 回答