将NSString中的出现次数替换为NSArray中的出现次数

时间:2012-07-23 17:03:53

标签: ios nsstring nsarray nslog

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

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

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

1 个答案:

答案 0 :(得分: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:@"?"];