Я застрял в iOS-приложении, которое работает на SQLite. Я создал Журнальный столик с различными типами кофе и именами, а также идентификатором кофе, который выступает в качестве первичного ключа. В SQLite я мог выполнять SQL-запросы и получать правильные ответы. Но, получая названия кофе в виде таблицы iOS, я ничего не получил, кроме пустой таблицы и заголовка раздела. При отладке кода я обнаружил, что while (sqlite3_step (selectstmt) == SQLITE_ROW) не работает, так как sqlite3_step (selectstmt) возвращает значение 101 (то есть SQLITE_DONE ) вместо SQLITE_ROW (то есть значение 100) , даже если я попытался с sqlite3_reset () перед выполнением sqlite3_step () .
Я не мог понять, как это решить. Мне нужна твоя помощь.
Вот мой код кофе.m
#import "Coffee.h"
#import "SQLAppDelegate.h"
static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
static sqlite3_stmt *addStmt = nil;
@implementation Coffee
@synthesize coffeeID, coffeeName, price, isDirty, isDetailViewHydrated;
- (void) dealloc {
[price release];
[coffeeName release];
[super dealloc];
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath{
SQLAppDelegate *appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];
if(sqlite3_open([dbPath UTF8String], &database)==SQLITE_OK){
const char *sql = "select CoffeeID, CoffeeName from Coffee";
sqlite3_stmt *selectstmt = nil;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL)== SQLITE_OK){
sqlite3_reset(selectstmt);
//NSLog(@"Macro %d",sqlite3_step(selectstmt));
while(sqlite3_step(selectstmt) == SQLITE_ROW){
NSInteger primaryKey = sqlite3_column_int(selectstmt,0);
NSLog(@"The P key is %d:",primaryKey);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.coffeeName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
coffeeObj.isDirty = NO;
[appDelegate.coffeeArray addObject:coffeeObj];
[coffeeObj release];
}
}
}
else
sqlite3_close(database);
}
- (id) initWithPrimaryKey:(NSInteger ) pk{
[super init];
coffeeID = pk;
NSLog(@"%d",coffeeID);
isDetailViewHydrated = NO;
return self;
}
+ (void)finalizeStatements {
if(database)
sqlite3_close(database);
}
@end
+++++++++++++++++++++++++++++++++++++++++ RootViewController.m ++++++++++++++++++
# import "RootViewController.h"
# import "Coffee.h"
@ реализация RootViewController
# Прагма Марк -
# pragma mark Просмотр жизненного цикла
- (void) viewDidLoad {
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication]delegate];
self.title = @"Name List";//Coffee List;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
# знак прагмы -
# pragma mark Источник данных табличного представления
// Настройка количества секций в табличном представлении.
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView {
return 1;
}
// Настройка количества строк в табличном представлении.
- (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) раздел {
NSLog(@"Rows %d",[appDelegate.coffeeArray count]);
return [appDelegate.coffeeArray count];
} * * тысяча пятьдесят-один
// Настройка внешнего вида ячеек табличного представления.
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
Coffee *coffeeObj = [appDelegate.coffeeArray objectAtIndex:indexPath.row];
cell.textLabel.text = coffeeObj.coffeeName;
return cell;
}
++++++++++++++++++++++++++++++++++++++++++++++++ SQLAppDelegate.m ++ +++++++++++++++++++++++++++++++++
# import "SQLAppDelegate.h"
# import "RootViewController.h"
# import "Coffee.h"
@ реализация SQLAppDelegate
@ синтезировать окно;
@ synthesize navigationController;
@ synthesize coffeeArray;
# Прагма Марк -
# прагма mark Жизненный цикл приложения
- (void) copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
// NSLog (@ "% @", dbPath);
BOOL success = [fileManager fileExistsAtPath:dbPath];
NSLog(@"%d",success);
if(!success){
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CoffeeDetail.sqlite"];
success =[fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if(!success)
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
//NSLog(@"dbpath %@",[documentDir stringByAppendingPathComponent:@"SQL.sqlite"]);
return [documentDir stringByAppendingPathComponent:@"CoffeeDetail.sqlite"];
}
- (void) удалитьCoffee: (Coffee *) coffeeObj {
//Delete from DataBase
[coffeeObj deleteCoffee];
//Delete from the array
[coffeeArray removeObject:coffeeObj];
}
- (void) applicationDidFinishLaunching: (UIApplication *) приложение {
[self copyDatabaseIfNeeded];
NSMutableArray *tempArray =[[NSMutableArray alloc]init];
self.coffeeArray = tempArray;
[tempArray release];
[Coffee getInitialDataToDisplay:[self getDBPath]];
NSLog(@"Array =%@", self.coffeeArray);
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
} * * 1 101
- (void) deleteCoffee {
if(deleteStmt == nil){
const char *sql = "delete from Coffee where coffeeID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
NSAssert1(0,@"Error while creating the delete Statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_int(deleteStmt, 1, coffeeID);
if(SQLITE_DONE != sqlite3_step(deleteStmt))
NSAssert1(0,@"Error while deleting. '%s'", sqlite3_errmsg(database));
sqlite3_reset(deleteStmt);
}