У меня есть база данных sqlite с именем 'ProductDatabase.sql', которую я скопировал в каталог проекта моего приложения:
/ Users / jacknutkins / Documents / TabbedDietApp / TabbedDietApp / ProductDatabase.sql
В классе делегатов приложения приложений у меня есть этот кусок кода:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Set-up some globals
m_DatabaseName = @"ProductDatabase.sql";
//Get the path to the documents directory and append the databaseName
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
m_DatabasePath = [documentsDirectory stringByAppendingPathComponent:@"ProductDatabase.sql"];
//Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];
//Query the databse for all animal records and construct the "animals" array
[self readProductsFromDatabase];
....
На данный момент:
m_DatabasePath = '/ Пользователи / jacknutkins / Библиотека / Поддержка приложений / iPhone Simulator / 5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/Library/ProductDatabase.sql'
Вот код для других 2 методов:
- (void) checkAndCreateDatabase {
NSError * error;
//Check if the database has been saved to the users phone, if not then copy it over
BOOL l_Success;
//Create a file manager object, we will use this to check the status
//of the databse and to copy it over if required
NSFileManager *l_FileManager = [NSFileManager defaultManager];
//Check if the database has already been created in the users filesystem
l_Success = [l_FileManager fileExistsAtPath:m_DatabasePath];
//If the database already exists then return without doing anything
if(l_Success)
return;
//If not then proceed to copy the database from the application to the users filesystem
//Get the path to the database in the application package
NSString *l_DatabasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:m_DatabaseName];
//Copy the database from the package to the usrrs filesystem
[l_FileManager copyItemAtPath:l_DatabasePathFromApp toPath:m_DatabasePath error:&error];
}
Если я выполню здесь несколько NSLogs:
l_DatabasePathFromApp = / Пользователи / jacknutkins / Библиотека / Поддержка приложений / iPhone Simulator / 5.0 / Приложения / 6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B / TabbedDietApp.app / ProductDatabase.sql
и:
ошибка = Ошибка домена = NSCocoaErrorDomain Code = 260 "Операция не может быть завершена. (Ошибка 260 какао.)" UserInfo = 0x6b6d060 {NSFilePath =/ Users / jacknutkins / Библиотека / Поддержка приложений / iPhone Simulator / 5.0 / Приложения / 6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B / TabbedDietApp.app / ProductDatabase.sql, NSUnderlyingError = 0x6b6cfa0 "Операция не может быть завершена.Нет такого файла или каталога "}
Я не уверен, что это за файл, который он не может найти здесь ..
- (void) readProductsFromDatabase {
//Init the products array
m_Products = [[NSMutableArray alloc] init];
NSLog(@"%@", m_DatabasePath);
//Open the database from the users filessystem
if(sqlite3_open([m_DatabasePath UTF8String], &database) == SQLITE_OK) {
//Set-up the SQL statement and compile it for faster access
const char *sqlStatement = "select * from products";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
NSLog(@"Success..");
//Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//Read the data from the results row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aCalories = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aFat = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aSaturates = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aSugar = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aFibre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aSalt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
NSString *aImageURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
NSLog(@"Delegate");
NSString *aNote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
NSUInteger myInt = sqlite3_column_int(compiledStatement, 11);
NSString *aServes = [NSString stringWithFormat:@"%d", myInt];
//Create a new animal object with the data from the database
Product *l_Product = [[Product alloc] initWithName:aName category:aCategory calories:aCalories fat:aFat saturates:aSaturates sugar:aSugar fibre:aFibre salt:aSalt imageURL:aImageURL note:aNote serves:aServes];
//Add the animal object to the animals array
[m_Products addObject:l_Product];
}
}
//Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
база данных объявлена в файле .h следующим образом:
//Setup the database object
sqlite3 *database;
В приведенном выше методе строка:
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
не оценивается как SQLITE_OK, поскольку база данных, которую я пытаюсь скопировать в каталог документов, пуста.
Я пытался очистить и собрать, удалить пустую копию базы данных, запустить ее и т. Д., Но она продолжает копировать пустую базу данных каждый раз.
Я несколько раз гуглил это и пыталсявсе, что я могу найти безуспешно ..
Любая помощь будет принята с благодарностью.
Джек
РЕДАКТИРОВАТЬ
Если явыполнить «выбрать * из продуктов» из окна терминала в базе данных в каталоге проекта, я верну ожидаемые результаты.