I have an NSMutableArray that I want to populate with an sqlite database and display the data in a table view. The app builds and shows "database opened" in the console but just shows an empty tableview, I had it working perfectly but suddenly it seems to have stopped working. here is the code for adding the data to the array:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize entries;
- (void)viewDidLoad
{
[super viewDidLoad];
//[entries addObject:@"object1"];
//[entries addObject:@"object2"];
//[entries addObject:@"object3"];
//[entries addObject:@"object4"];
[self openDB];
entries = [[NSMutableArray alloc] init];
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM speakers ORDER BY name"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW) {
char *field2 = (char *) sqlite3_column_text(statement,1);
NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];
NSString *str = [[NSString alloc]initWithFormat:@"%@", field2Str];
[entries addObject:str ];
}
}
}
//file path to db
-(NSString *) filePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"speakerdb.sqlite"];
}
//open the db
-(void)openDB {
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK){
sqlite3_close(db);
NSAssert(0,@"error preparing statement: %s", sqlite3_errmsg(db));
}else{
NSLog(@"database opened");
}
}
The NSMutableArray is defined in the header file as follows:
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "speakerViewController.h"
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
IBOutlet UITableView *theTable;
sqlite3 *db;
}
@property (nonatomic,retain) NSMutableArray *entries;
@end
Here is the code for adding the data to the table view:
-(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 [entries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//Congigure the cell...
cell.textLabel.text = [entries objectAtIndex:indexPath.row];
return cell;
}
The data shows in the table view if I add objects to the array manually (commented out lines shown in the viewDidLoad method) but doesnt seem to work from the sqlite database.
Any help would be much appreciated.
Edit: I'm using xcode 5.1.1