1

我正在寻找一种在 iOS 应用程序中调试我的 SQLite 查询的快速方法。我有这样的事情:

NSString *sql = [NSString stringWithString: @"SELECT * FROM table WHERE foo = ? AND bar = ?"]; 
NSArray *params = [NSArray arrayWithObjects: @"baz", @"bat", nil];
NSLog(@"%@ %@", sql, params);

我想知道是否有一个或两个行来用参数替换问号以使输出更具可读性。我不是在寻找输出有效 sql 的东西,而是寻找比我当前的 NSLog 更容易阅读的东西。

4

1 回答 1

1
@interface NSString (SQLQueryDebugging)
- (NSString *)stringBySubstitutingParameters:(NSArray *)params forInstancesOfPlaceholder:(NSString *)placeholder;
@end

@implementation NSString (SQLQueryDebugging)

- (NSString *)stringBySubstitutingParameters:(NSArray *)params forInstancesOfPlaceholder:(NSString *)placeholder
{
    NSString *composedQuery = self;
    NSRange substitutionRange = [composedQuery rangeOfString:placeholder];
    NSInteger parameterIndex = 0;
    while(substitutionRange.length != 0)
    {
        NSString *currentParam = [params objectAtIndex:parameterIndex];
        composedQuery = [composedQuery stringByReplacingCharactersInRange:substitutionRange withString:currentParam];
        ++parameterIndex;
        NSInteger lastSubstitutionIndex = substitutionRange.location + [currentParam length];
        NSRange searchRange = NSMakeRange(lastSubstitutionIndex, [composedQuery length] - lastSubstitutionIndex);
        substitutionRange = [composedQuery rangeOfString:placeholder options:0 range:searchRange];
    }

    return composedQuery;
}

把它放在某个地方,然后你可以得到你想要的:

NSString *completeSQL = [sql stringBySubstitutingParameters:params forInstancesOfPlaceholder:@"?"];
于 2012-07-23T17:18:12.100 回答