在iOS应用程序中使用现有数据
我对iOS开发相当陌生,肯定不完全了解在iOS应用程序中使用现有数据,ios,xcode,sqlite,Ios,Xcode,Sqlite,我对iOS开发相当陌生,肯定不完全了解Xcode等的工作原理。我正在创建一个iOS应用程序,并一直在使用Sqlite在设备上存储数据。我在项目中添加了一个sqlite3数据库,但我注意到在模拟器中,数据库在应用程序第一次运行时并不存在,因此必须在代码中创建。到现在为止,这还可以。我应该有一份清单,上面写着申请表应该随附的日期。是否可以让应用程序在第一次运行时使用包含某些数据的数据库?这是因为sqlite文件在您的包中 启动ApplicationIDFinish后,需要将其移动到库文件夹(或文档文
Xcode
等的工作原理。我正在创建一个iOS应用程序,并一直在使用Sqlite
在设备上存储数据。我在项目中添加了一个sqlite3
数据库,但我注意到在模拟器中,数据库在应用程序第一次运行时并不存在,因此必须在代码中创建。到现在为止,这还可以。我应该有一份清单,上面写着申请表应该随附的日期。是否可以让应用程序在第一次运行时使用包含某些数据的数据库?这是因为sqlite文件在您的包中
启动ApplicationIDFinish后,需要将其移动到库文件夹(或文档文件夹)
有关详细信息,请签出NSFileManager
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bookdb.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
如果sqlite数据库不存在,则通过该数据库进行复制
希望这能有所帮助。的可能重复-即使这个问题是针对核心数据的,答案也适用于默认的sqlite文件。感谢您的回答,我将尝试这个。所以没有必要使用CoreData?CoreData无论如何都是基于sqlite3的。大多数情况下,文件应该被移动或创建到库文件夹中。非常感谢!这很好用。我已经编写了一些代码,但由于某种原因它无法工作。唯一的区别是,在我的代码中,我使用mainbundle上的pathForResource来查找我的数据库文件,它似乎返回了正确的路径,但在复制时,我收到了cocoa错误4(这不太清楚)。放入应用程序:didFinishLaunchingWithOptions:method of appdelegate。我确实将代码放入其中,在didFinishLaunchingWithOptions中