我想用SQLite创建一个待办事项列表,我一直在学习本教程:http://klanguedoc.hubpages.com/hub/IOS-5-How-To-Display-SQLite-Data-in-a-UITableView但它不起作用!模拟器运行,应用程序打开,但表为空。我做错什么了吗?我正在为雪豹使用xcode 4.2。
在.sqlite文件中,我有一个字符串文本、整数优先级和布尔完成。然而,我只是实现了"文本",使事情变得更简单。
这是我的代码:
// Title.h
#import <Foundation/Foundation.h>
@interface Title : NSObject {
NSString *text;
}
@property(nonatomic,copy) NSString *text;
@end
//TitleVC.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
@interface TitleVC : UITableViewController{
NSMutableArray *thelist;
sqlite3 *db;
}
@property (nonatomic,retain) NSMutableArray *thelist;
-(NSMutableArray *) toDo;
@end
//TitleVC.m
#import "TitleVC.h"
#import "Title.h"
#import <sqlite3.h>
@implementation TitleVC
@synthesize thelist;
- (void)viewDidLoad
{
[self toDo];
[super viewDidLoad];
}
- (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.thelist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"TitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
int rowCount = indexPath.row;
Title *title = [self.thelist objectAtIndex:rowCount];
cell.textLabel.text = title.text;
return cell;
}
-(NSMutableArray *) toDo{
thelist = [[NSMutableArray alloc] initWithCapacity:10];
@try{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"todo.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate database file '%@'.",dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(@"An error has occured: %@",sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM todo";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db));
}else{
Title *title = [[Title alloc] init];
while (sqlite3_step(sqlStatement)==SQLITE_ROW){
title.text = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
[thelist addObject:title];
}
}
}
@catch (NSException *exception) {
NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db));
}
@finally {
return thelist;
}
}
如果使用标准UITableView,tableView:numberOfRowsInSection:是否返回适当的值?什么是tableView:cellForRowAtIndexPath:正在返回?我会在这两个位置都放置一个断点,并检查这些方法是否被调用。
最后,如果您使用的是.xib文件,是否有到UITableView的连接?