我试图从SQlite表中检索结果,然后将它们分配给Objective-C中的变量。我这样做的方法如下:
- (void) readRestaurantsFromDatabase {
//Setup the database object
sqlite3 *database;
//Init the restaurant array
restaurants = [[NSMutableArray alloc] init];
//Open the database from the users filesystem
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
//setup the SQL statement and compile it for faster access
const char *sqlStatement = "select * from restaurant";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
//read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 2)];
NSString *aCity = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 3)];
NSString *aProvinceState = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 4)];
NSString *aPostalZipCode = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 5)];
NSString *aCountry = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 6)];
NSString *aPhoneNumber = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 7)];
NSString *aHours = [NSString stringWithUTF8String:(char *)sqlite_coluumn_text(compiledStatement, 8)];
//double aLat
//double aLon
Restaurant *restaurant = [[Restaurant alloc] initWithName:aName address:aAddress city:aCity provinceState:aProvinceState postalZipCode:aPostalZipCode country:aCountry phoneNumber:aPhoneNumber hours:aHours latitude:aLat longitude:aLon];
//add the restaurant object to the restaurant array
[restaurants addObject:restaurant];
[restaurant release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
从sqlite表中检索字符串时没有问题。我的困惑是如何从SQLite表中检索存储为双精度的纬度和经度变量?我如何将这些值分配给变量double aLat,并在上面的代码中加倍aLon?
使用sqlite_column_double
。就那么简单:
double aLon = sqlite_column_double(compiledStatement, 9);
double aLat = sqlite_column_double(compiledStatement, 10);
我能想到的最简单的方法是使用float创建一个NSNumber并从中获取double值:
NSNumber *number = [NSNumber numberWithFloat:aFloat];
double aDouble = [number doubleValue];
正如你在其他领域所做的那样。您可以检索它并将双值作为字符串。我还建议你创建一本字典。您可以将所有数据存储在字典中。然后,您可以在Objective C代码中访问它。