2013-01-02 3 views
6

이제 NSPredicate에서 작은 따옴표 (') 문제가 있습니다. NSPredicate 작은 따옴표 문제

NSPredicate *query = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"s_name='%@' AND s_regno=%d",Name,[RegNo intValue]]]; 

내가 이름으로 필터링

는 "존", 그것은 확인하고 전혀 오류 :

여기 내 쿼리입니다. 하지만 저는 "Mary Monny"라는 이름을 사용합니다. 오류가 있습니다.

작은 따옴표로 추정됩니다. pls이 문제를 극복하는 방법을 도와주세요.

감사

답변

1

이름 = @ "벨"이 같은 술어를 만들려고 할 수있는 경우 :

NSPredicate *query = [NSPredicate predicateWithFormat:@"name == \"%@\"", name]; 

그냥 따옴표 표준 작은 따옴표를 대체합니다.

+3

그리고 입력 문자열에 큰 따옴표가 있으면 무엇입니까? – northernman

12

은 빠른 수정, 당신은 모두의 NSString 부분을 필요가 없습니다. 이 대체 방법은 predicateWithFormat: 메소드의 요점입니다! 간단히 사용하십시오 :

NSPredicate *query = [NSPredicate predicateWithFormat:@"s_name == %@ AND s_regno == %d", Name, [RegNo intValue]]; 

저는 형식 문자열을 완전히 피하고 대신 코드에서 조건자를 작성합니다. 내가 s_name like[cd] %@ 같이 이름에 소문자와 분음 부호를 구분 비교를 할 NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption을 추가

NSPredicate *nameQuery = 
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_name"] 
            rightExpression:[NSExpression expressionForConstantValue:Name] 
              modifier:NSDirectPredicateModifier 
               type:NSLikePredicateOperatorType 
              options:NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption]; 

NSPredicate *regNoQuery = 
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_regno"] 
            rightExpression:[NSExpression expressionForConstantValue:RegNo] 
              modifier:NSDirectPredicateModifier 
               type:NSEqualToPredicateOperatorType 
              options:0]; 

NSPredicate *query = [NSCompoundPredicate andPredicateWithSubpredicates:@[nameQuery,regNoQuery]]; 

참고. 필요하지 않으면 물론 type:NSEqualToPredicateOperatorTypeoptions:0을 사용할 수 있습니다.

+0

"빠른 수정"이 정답입니다. –

+0

정답으로 표시해야합니다. – northernman