在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber

How to call and convert an int/NSNumber when calling on a sqlite3 database in Objective-C?

本文关键字:调用 转换 int NSNumber sqlite3 Objective-C 数据库 何调用      更新时间:2023-10-16

提前感谢您抽出时间阅读并希望为我提供帮助。我对编码相对陌生,目前面临的问题是;

我构建了一个sqlite3数据库,有三列,分别存储为;字符串、float和int。当试图读取和表示列时,我很难找到一个表示float和整型值的方法。

存储在数据库中的三个属性设置为;

@property (nonatomic, strong) NSString *name;
@property (nonaomtic, strong) NSNumber *price;
@property (nonaomtic, strong) NSNumber *quantity;

我不确定将后两个属性更改为float和int是否会有所不同?

然而,对我来说,主要的困惑在于我为了调用数据库而编写的以下代码;

-(void)readDataFromDatabase{
[self.stock removeAllObjects];
sqlite3 *database;
if (sqlite_open([self.databasePath UTF8String], &database) == SQLITE_OK) {
char *sqlStatement = "select * from entries";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK){
while(sqlite3_step(compiledStatement) == SQLITE_ROW{
char *n = sqlite3_column_text(compiledStatement, 1);
char *p = sqlite3_column_int(compiledStatement, 2);
chat *q = sqlite3_column_int(compiledStatement, 3);
NSString *name = [NSString stringWithUTF8String:n];
NSNumber *price = [NSString stringWithUTF8String:p];
NSNumber *quantity = [NSString stringWithUTF8String:q];
Data *data = [[Data alloc] initWithData:name thePrice: price theQuantity:quantity];
[self.stock addObject:data];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}

我的常识告诉我问题在于这一部分;

NSString *name = [NSString stringWithUTF8String:n];
NSNumber *price = [NSString stringWithUTF8String:p];
NSNumber *quantity = [NSString stringWithUTF8String:q];

我不确定该如何处理NSNumber?我知道NSString字符串WithUTF8String是不正确的,但我不知道NSNumber的等价项。

我真的很感激在这件事上有任何见解和帮助。

谢谢!

您对floatint所做的介绍是正确的。Float不需要像NSString那样被引用,因为它的大小在32位和64位系统之间没有变化。如果你的整数更大,那么我建议使用NSInteger作为该值:

char *n = sqlite3_column_text(compiledStatement, 1);
float p = sqlite3_column_text(compiledStatement, 2);
int q = sqlite3_column_text(compiledStatement, 3);
NSString *name = [NSString stringWithUTF8String:n];
float price = p;
NSInteger quantity = q;

注意:您不需要为float或int值指定*,因为它们不是指针。

你甚至可以只做(如果你已经在你的头中声明了属性):

name = [NSString stringWithUTF8String:sqlite3_column_text(compiledStatement, 1)];
price = sqlite3_column_text(compiledStatement, 2);
quantity = sqlite3_column_text(compiledStatement, 3);

要检查值,可以使用NSLog:

NSLog(@"%@ %.02f %li", name, price, quantity);

为了完整起见,如果您想将floatint制作成NSNumber:

NSString *name = [NSString stringWithUTF8String:n];
NSNumber *price = [NSNumber numberWithFloat:p];
NSNumber *quantity = [NSNumber numberWithInt:q];

标题中的属性声明为:

name = [NSString stringWithUTF8String:n];
value = [NSNumber numberWithFloat:p];
quantity = [NSNumber numberWithInt:q];
NSLog(@"%@ %@.02f %@", name, price, quantity);

有多种方法可以获得结果,这就是Objective-C非常灵活的原因。