2013-05-28 3 views
7

가 포함 된 경우 내가 내 응용 프로그램에서 다음과 같은 데이터 모델이 : data modelCoreData 검사가-많은 관계 객체

는 기본적으로 나는 도시의 이름으로 aswell 국가 이름을 저장할합니다. 각 도시는 한 국가에 속하고 한 국가에는 0 - n 개의 도시가 있습니다.

특정 도시에 새로운 도시를 추가하기 전에 해당 도시에이 도시 이름이 이미 있는지 알아야합니다.

지금까지 내가 이렇게 : 나는 동등한이 올바른 술어 페치 필요

- (BOOL)countryForName:(NSString *)countryName containsCity:(NSString *)cityName { 
    Countries *country = [self countryForName:countryName]; 
    NSSet *cityNames = [country valueForKey:@"cities"]; 
    for (Cities *city in cityNames) { 
     if ([city.cityName isEqualToString:cityName]) { 
      return YES; 
     } 
    } 
    return NO; 
} 

이것은 분명히 매우 느립니다. 다음과 같은 하나의 엔티티에 대한 검색을 수행합니다.

NSEntityDescription *entity  = [NSEntityDescription entityForName:@"Countries" inManagedObjectContext:self.managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    // Edit the sort key as appropriate. 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countryName" ascending:YES]; 
    NSArray *sortDescriptors   = @[sortDescriptor]; 
    fetchRequest.sortDescriptors  = sortDescriptors; 

    // Edit the section name key path and cache name if appropriate. 
    // nil for section name key path means "no sections". 
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"GetCountryList"]; 
    aFetchedResultsController.delegate = self; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryName == %@", countryName]; 
    [aFetchedResultsController.fetchRequest setPredicate:predicate]; 

그러나 검색에 여러 엔티티가 관련된 경우 어떻게해야합니까? 또는 다른 말로하면 : 한 국가에만 고유 한 도시 이름을 어떻게 추가합니까?
대단히 감사합니다! 당신이 특정 국가의 객체가 이미 이름을 가진 도시가 포함되어 있는지 확인하려면

답변

11

, 당신은 가져 오기 요청을 사용하여,

Countries *country = ... 
NSString *cityName = ... 
if ([[country valueForKeyPath:@"cities.name"] containsObject:cityName]) { 
    // ... 
} 

을하거나 할 수 있습니다 : • 그래도

NSString *countryName = ... 
NSString *cityName = ... 
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Countries"]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryName == %@ AND ANY cities.cityName == %@", countryName, cityName]; 
[fetchRequest setPredicate:predicate]; 

NSError *error; 
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error]; 

if (count == NSNotFound) { 
    // error 
} else if (count == 0) { 
    // no matching country 
} else { 
    // at least one matching country 
} 

NSFetchedResultsController은 일반적으로 가져 오기 요청의 내용을 테이블보기에 표시하는 데 사용되므로 여기서는 필요하지 않습니다.

+0

안녕 마틴,이 답장을 보내 주셔서 감사합니다. 이 솔루션은 내 코드가 거의 개선되지 않은 것처럼 보입니다. fetchrequest를 생성 한 다음'countForFetchRequest :'를 수행 할 수있는 방법이 없나요? "국가는이 도시를 포함하고 있지 않습니다"또는 0을 "국가는이 도시를 포함합니다"로 반환합니까? 메모리 사용량을 줄이기 위해 객체를 만드는 것을 좋아하지 않습니다 ... – pmk

+0

@pmk : 당신 말이 맞습니다. 답변을 업데이트했습니다. –

+0

방금 ​​코드를 테스트했습니다. 이제 완벽하게 작동합니다. 다른 사람들이 활용할 수 있도록 답변 코드를 편집했습니다. 매우 감사드립니다. – pmk