【问题标题】:NSInteger and int giving exceptionsNSInteger 和 int 给出异常
【发布时间】:2011-08-10 12:05:06
【问题描述】:

我正在尝试使用 FMDB 从数据库中获取数据,但尝试了一段时间但徒劳无功,我无法弄清楚为什么会引发 EXC_BAD_ACCESS 异常。该参数是从 NSInteger 传入的,但我既不能记录它,也不能在 SELECT 语句中使用它。我的代码是:

-(SQLiteResult*) getClient:(bool)forceRefresh id:(NSString*)id forYear:(NSInteger)year {
    SQLiteResult *res;
    if(!forceRefresh){
        NSMutableArray *hereditaments = [[NSMutableArray alloc] init];
        NSLog([NSString stringWithFormat:@"SELECT * FROM Clients WHERE ID = %@ AND Year = %@", id, [NSString stringWithFormat:@"%@", year]]); // exception
        NSLog([NSString stringWithFormat:@"SELECT * FROM Clients WHERE ID = %@ AND Year = %@", id, year]]); // also exception
        FMResultSet *rs = [db executeQuery:[NSString stringWithFormat: @"SELECT * FROM Clients WHERE ID = ? AND Year = %@", year], id]; // also exception
        FMResultSet *rs = [db executeQuery:[NSString stringWithFormat: @"SELECT * FROM Clients WHERE ID = ? AND Year = ?", id, year]]; // also exception

我即将将其作为字符串传递。有没有一种安全的方法可以只在 SQL 语句中使用年份?

【问题讨论】:

    标签: iphone objective-c ios nsinteger sqldatatypes


    【解决方案1】:

    NSInteger 不是对象类型。它只是 int 类型的 typedef。因此,您不能使用%@ 作为格式说明符。你应该使用%d

    【讨论】:

      【解决方案2】:

      由于您的 year 变量是 NSInteger 类型,您应该在创建 NSString 时使用 %d 格式而不是 %@

      【讨论】:

      • 将其格式化为 %d 而不是将其作为参数传递给查询。谢谢。
      猜你喜欢
      • 2011-11-29
      • 2023-03-12
      • 2010-12-28
      • 1970-01-01
      • 2011-08-26
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多