出于测试目的,我一直在我的应用程序的支持文件中删除我的 sqlite DB。我目前正在尝试将其移至 URL,因此我将能够在不更新应用程序的情况下更新数据库。我正在使用以下代码,它似乎正在工作,因为它将文件下载到文档目录。问题是我已经从支持文件中删除了旧数据库,并且它的数据仍在被提取。我在我的数据库中进行了更改,所以我会知道其中的区别。
我需要清除一些记忆吗?如果不是我在这里想念什么。
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *file = [NSString stringWithFormat:@"http://www.myurl/TulsaListBars.sqlite"];
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
fileData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[fileData setLength:0];
totalFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[fileData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [dirArray objectAtIndex:0]);
NSString *path = [NSString stringWithFormat:@"%@/TulsaListBar.sqlite", [dirArray objectAtIndex:0]];
if ([fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(@"writeToFile error");
}
else {
NSLog(@"Written!");
}
}
以下代码是我阅读数据库的方式。
-(NSMutableArray *) barList{
thebars = [[NSMutableArray alloc] init];
@try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"TulsaListBars.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate database file '%@'.", dbPath);
}else{
NSLog(@"File Exists: %@", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(@"An error has occured: %s", sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM Locations WHERE bar = 'yes'";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Bar * bar = [[Bar alloc] init];
bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
etc.....