1
夥計,取回核心數據的重複記錄
我在我的iPhone項目中有一個涉及Core Data的益智遊戲。在兩個獨立的視圖控制器實例viewDidLoad方法我調用下面的方法:
- (NSFetchedResultsController *)getStudentResults:(NSString *)classRoom forWeekStarting:(NSDate *)startDate andEnding:(NSDate *)endDate {
AttendanceAppDelegate *appDelegate = (AttendanceAppDelegate *)[[UIApplication sharedApplication] delegate];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[appDelegate managedObjectContext]];
int secondsInAWeek = 60 * 60 * 24 * 7;
NSDate *today = [[NSDate alloc] init];
NSDate *nextWeek = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsInAWeek];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(student.classRoom like %@) AND (dateTime >= %@) AND (dateTime <= %@)", classRoom, startDate, endDate];
[request setPredicate:predicate];
[request setEntity:entityDescription];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateTime" ascending:YES];
NSArray *descriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:descriptors];
[descriptors release];
[sortDescriptor release];
[nextWeek release];
[today release];
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[appDelegate managedObjectContext] sectionNameKeyPath:nil cacheName:@""];
NSError *error;
if (![fetchedResultsController performFetch:&error])
NSLog(@"Error performing fetch on fetchedResultsController: %@", [error localizedDescription]);
if (fetchedResultsController == nil || [[fetchedResultsController fetchedObjects] count] == 0) {
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:[appDelegate managedObjectContext]];
NSData *classRoomStudentData = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"STUDENT_ATTENDANCE" ofType:@"XML"]];
[student setClassRoom:@"default"];
[student buildWithStudentData:classRoomStudentData startingWithXPathNode:@"//attendance"];
NSError *error;
if (![[appDelegate managedObjectContext] save:&error]) {
NSLog(@"Error saving the managedObjectContext: %@", [error localizedDescription]);
}
if (![fetchedResultsController performFetch:&error])
NSLog(@"Error performing fetch on fetchedResultsController: %@", [error localizedDescription]);
}
return fetchedResultsController;
}
每次我跑我的應用程序的學生對象的數量由原來的實體的數量增加(每個原始實體重複一次)。所以,如果我從4開始,下一次我得到8,然後12,然後16等。我似乎無法弄清楚爲什麼,因爲解析XML的代碼僅在fetch返回對象時才被調用。
任何幫助,將不勝感激,謝謝。
邁克爾 -
你是絕對正確的,我只是通過代碼加強第二次,發現要求不是「默認」以外的教室的時候XML將被再次解析。感謝指針。 – 2009-09-21 16:39:25