使用SQLite信息加载表视图(在视图控制器内)

时间:2013-06-10 18:01:15

标签: ios xcode uitableview sqlite

我有一个将信息插入数据库的视图。此视图在表视图中显示该信息(视图的上半部分用于其他内容)

我有视图控制器的类,一个对象类和一个表视图单元类(这就是我想的,因为图像和文本标签在这里,而实际的数据库信息在视图控制器中)。

这是NSObject类:

// car.h
#import <Foundation/Foundation.h>

@interface Car : NSObject {
    NSString *displayedMake;
    NSString *displayedModel;
    NSString *displayedImage;
}

@property (nonatomic, strong) NSString *displayedMake;
@property (nonatomic, strong) NSString *displayedModel;
@property (nonatomic, strong) NSString *displayedImage;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u;

@end 

//car.m
#import "Car.h"

@implementation Car
@synthesize displayedMake, displayedModel, displayedImage;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u {
    self.displayedMake = n;
    self.displayedModel = d;
    self.displayedImage = u;
    return self;
}

@end

这是表格视图单元格类:

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

@interface DisplayCarsCell : UITableViewCell
@property (nonatomic, strong) IBOutlet UIImageView *carImage;
@property (nonatomic, strong) IBOutlet UILabel *makeLabel;
@property (nonatomic, strong) IBOutlet UILabel *modelLabel;
@end

//DisplayCarsCell.m
#import "DisplayCarsCell.h"
#import "ViewController.h"

@implementation DisplayCarsCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code           
    }
    return self;
}    
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{       
    [super setSelected:selected animated:animated];    
    // Configure the view for the selected state
}    
@end

最后,视图控制器:

//ViewController.h
#import <UIKit/UIKit.h>
#import "/usr/include/sqlite3.h"

@interface ViewController : UIViewController <UITableViewDelegate> {
    //NSString    *databasePath;
    sqlite3     *carsDB;
    NSArray     *carImages;
   NSMutableArray *cars;
}
@property (nonatomic, retain) NSMutableArray *cars;
@property (strong, nonatomic) IBOutlet UILabel *status;    
@end


//ViewController.m

#import "ViewController.h"
#import "DisplayCarsCell.h"
#import "Car.h"

@interface ViewController () 
@end

@implementation ViewController
@synthesize cars;

-(NSString *) filePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"cars.db"];
}    
-(void) openDB {
    if (sqlite3_open([[self filePath]UTF8String],&carsDB) != SQLITE_OK){
        sqlite3_close(carsDB);
        NSAssert(0, @"Database failed to open");
    }
    else{
        NSLog(@"database opened");
    }
}        
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // Opens the database and creates the table if its the first time       
    [self readCarsFromDatabase];            
}        
- (void)readCarsFromDatabase
{
    // Setup the database object
    //sqlite3 *database;        
    // Init the animals Array
    cars = [[NSMutableArray alloc] init];       
    // Open the database from the users filessytem
    [self openDB];
    const char *sql_stmt = "CREATE TABLE IF NOT EXISTS apps (name text, id text, image text)";            
        if (sqlite3_exec(carsDB, sql_stmt, NULL, NULL, NULL) == SQLITE_OK)
        {
            NSLog(@"create db");
        }
        //Setup the SQL Statement and compile it for faster access          
        const char *sqlStatement = "select * from apps";
        sqlite3_stmt *compiledStatement;           
        if(sqlite3_prepare_v2(carsDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {                
         // Loop through the results and add them to the feeds array
         while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
         // Read the data from the result row               
         //image, or first column in table
         NSString *displayedImage=[NSString stringWithFormat: @"%s",(const char *)sqlite3_column_text(compiledStatement, 0)];                        
         //name, or second column in table
         NSString *displayedMake=[NSString stringWithFormat: @"%s",(const char *)sqlite3_column_text(compiledStatement, 1)];                    
         //model, or third column in table
         NSString *displayedModel=[NSString stringWithFormat: @"%s",(const char *)sqlite3_column_text(compiledStatement, 2)];                    
         NSLog(@"%@, %@, %@",displayedImage, displayedMake, displayedModel);
                _status.text = displayedMake;                
         NSLog(@"here");
         // Create a new animal object with the data from the database
         Car *carObject = [Car alloc];
         carObject.displayedImage = [NSString stringWithFormat: @"%s",(const char *)sqlite3_column_text(compiledStatement, 0)];                   
         // Add the animal object to the animals Array
         [cars addObject:carObject];
         //NSLog(@"%@",displayedImage);
            }                               
        }
        else
        {
            printf( "could not prepare statement: %s\n", sqlite3_errmsg(carsDB) );
        }            
        // Release the compiled statement from memory
            sqlite3_finalize(compiledStatement);                    
            sqlite3_close(carsDB);    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}    
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{        
    // Return the number of rows in the section.
    return carImages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"DisplayCarsCell";        
    DisplayCarsCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[DisplayCarsCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }        
    // Configure the cell...        
    //UIImage *displayedImage = [UIImage imageNamed:
    //[carImage objectAtIndex: [indexPath row]]];        
    //   Car *carObj = [cars objectAtIndex:indexPath.row];            
    ViewController *viewController = (ViewController *)[[UIApplication sharedApplication] delegate];
    Car *car = (Car *)[viewController.cars objectAtIndex:indexPath.row];        
    //[cell setImage:car.displayedImage];        
    return cell;        
}        
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO: Select Item
    NSLog(@"Selected");}    
@end

视图控制器本身显然是从readCarsFromDatabase获取数据数组,并正在viewDidLoad上正确记录数据库的每一行(这样做是为了确保该部分没有错误),但我需要它来更新行内部的表视图。

1 个答案:

答案 0 :(得分:0)

完成向reloadData添加记录后,您必须为{1}}调用cars,例如在readCarsFromDatabase结束时。我没有看到IBOutlet的{​​{1}},但如果只是UITableView,那么您需要在tableView之后添加一行说明:

sqlite3_close

显然,请确保将表视图的委托设置为视图控制器。


另外,我原本会想到视图控制器的[self.tableView reloadData]; 中的以下行:

cellForRowAtIndexPath

应改为简单地说:

ViewController *viewController = (ViewController *)[[UIApplication sharedApplication] delegate];
Car *car = (Car *)[viewController.cars objectAtIndex:indexPath.row];