2014-07-13 2 views
0

NSPredicate를 사용하여 객체를 가져 오는 데 "startswith [cp]"조건을 설정하는 방법을 찾고 있습니다. 데이터 모델에는 4 개의 기본 속성을 포함하는 하나의 엔티티가 있습니다. 첫 번째 속성의 이름은 cityName입니다. 목표는 cityName이 주어진 문자로 시작하는 레코드를 찾는 것입니다. 그러나 술어를 형식화하는 방법을 모르겠습니다. 이이핵심 데이터 및 NSPredicate

NSString * lastCharacter = [userCity substringFromIndex:[userCity length] -1]; 
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
NSManagedObjectContext *context = 
[appDelegate managedObjectContext]; 

NSEntityDescription *entityDesc = 
[NSEntityDescription entityForName:@"Cities" 
      inManagedObjectContext:context]; 

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entityDesc]; 

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(cityName = beginswith [cp] %@)", lastCharacter]; 
[request setPredicate:pred]; 

에 대한 내 코드의 일부하지만,이 코드를 나는 오류 다음 얻을 :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(cityName = beginswith [cp] %@)"' 
+0

나에게 보인다. – RegularExpression

답변

1

문제는 beginswith 그렇게 = beginswith 너무 많이 하나, 운영자 때문이다 . 술어의 대괄호도 필요하지 않습니다. 따라서 :

[NSPredicate predicateWithFormat:@"cityName beginswith[cd] %@", lastCharacter]; 
+0

내 코드의 첫 번째 부분이 정확합니다. 문자열의 마지막 문자를 얻으려면 [string substringFromIndex : [string length] -1]을 사용해야합니다. 두 번째 부분은 내 문제를 해결하는 데 도움이됩니다. –

0

그냥 같이 당신의 조건을 변경 : - 문제가 lastCharacter의 값처럼

NSPredicate *pred = [NSPredicate predicateWithFormat:@"cityName contains[cd] %@",lastCharacter];