我有一个(nsdictionary*record)带有键attr1、attr2、attr3。
我有一个动态where子句,需要应用到sql lite数据库。但是在构造fetch请求之前,谓词必须是“attr1=%@和attr2=%@以及attr3=%@”格式。此外,我还有一个静态字符串whereclause,其定义格式为“attr1=:attr1和attr2=:attr2和attr3=:attr3”(注意:此格式是不可更改的。它是在客户的生产服务器上定义的)。动态的意思是“:attr1”、“:attr2”、“:attr3”应该被上面提到的字典变量记录中的值替换。
所以要创建一个谓词,需要创建以下字符串和属性数组,以便执行fetch请求。
“attr1=%@和attr2=%@和attr3=%@”
[“attr1”,“attr2”,“attr3”]
我找到的解决方案如下:
NSString * whereClause = @"ATTR1=:ATTR1 AND ATTR2=:ATTR2 AND ATTR3=:ATTR3";
NSArray * primaryTokens = [whereClause componentsSeparatedByString: @":"];
NSUInteger primaryTokenCount = [primaryTokens count];
NSMutableString * finalWhereClause = [[NSMutableString alloc] initWithString:primaryTokens[0]];
NSMutableArray * attributes = [[NSMutableArray alloc]init];
if(primaryTokenCount >1)
{
for(int i=0;i<(primaryTokenCount-1);i++){
NSArray * secondaryTokens = [primaryTokens[i+1] componentsSeparatedByString: @" "];
NSUInteger secondaryTokenCount = [secondaryTokens count];
if(secondaryTokenCount > 1)
{
[finalWhereClause appendString:@"%@"];
NSArray * newSecondaryArray = [secondaryTokens subarrayWithRange:NSMakeRange(1,[secondaryTokens count]-1)];
[finalWhereClause appendString:@" "];
[finalWhereClause appendString:[newSecondaryArray componentsJoinedByString:@" "]];
}
[attributes addObject:secondaryTokens[0]];
}
[finalWhereClause appendString:@"%@"];
}
NSLog(@"THE FINAL PARSED STRING IS : %@",finalWhereClause);
NSLog(@"THE FINAL ATTRIBUTES IS : %@",[attributes componentsJoinedByString:@","]);
以上代码有效。但它的开销是在主循环的每次运行中使用3个额外的数组并按组件进行分离在目标C中是否有一种有效的方法来实现这种解析,从而避免这种过度的额外存储这种方法将被广泛地调用因此,任何帮助都将不胜感激。
最佳答案
NSString *whereClause = @"ATTR1=:ATTR1 AND ATTR2=:ATTR2 AND ATTR3=:ATTR3";
NSString *finalWhereClause = whereClause;
NSArray *clauseComponents = [whereClause componentsSeparatedByString: @" "];
NSMutableArray *attributes = [NSMutableArray new];
for (NSString *component in clauseComponents) {
if ([component containsString:@":"]) {
NSString *paramName = [component substringFromIndex:[component rangeOfString:@":"].location + 1];
[attributes addObject:paramName];
NSString *separatedParamName = [@":" stringByAppendingString:paramName];
finalWhereClause = [finalWhereClause stringByReplacingOccurrencesOfString:separatedParamName withString:@"%@"];
}
}
NSLog(@"THE FINAL PARSED STRING IS : %@",finalWhereClause);
NSLog(@"THE FINAL ATTRIBUTES IS : %@",[attributes componentsJoinedByString:@","]);