我有一個列表,我試圖在iOS5應用中導入一個rails應用程序。每個地方都有一個父母,這是一個地方。核心數據:使用查找或插入/重複條目導入樹結構
我試圖使用字典
- (void)initWithDictionary:(NSDictionary *)dictionary {
self.placeId = [dictionary valueForKey:@"id"];
id parent = [dictionary objectForKey:@"parent"];
if (parent && parent != [NSNull null]) {
NSDictionary *parentDictionary = parent;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"placeId = %@", [parentDictionary objectForKey:@"id"]];
NSArray *matching = fetchedWithPredicate(@"Place", self.managedObjectContext, predicate, nil);
if ([matching count] > 0) {
self.parent = [matching objectAtIndex:0];
} else {
self.parent = [NSEntityDescription insertNewObjectForEntityForName:@"Place" inManagedObjectContext:self.managedObjectContext];
[self.parent initWithDictionary:parentDictionary];
}
}
}
fetchedWithPredicate導入與核心數據即JSON數據是被定義爲這樣
NSArray* fetchedWithPredicate(NSString *entityName, NSManagedObjectContext *context, NSPredicate *predicate, NSError **error) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setIncludesPendingChanges:YES];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:entity];
[request setPredicate:predicate];
NSArray *result = [context executeFetchRequest:request error:error];
return result;
}
的方法我也有在Place.m驗證方法以確保我不創建與placeId相同的位置(placeId是服務器端的id)。
- (BOOL)validatePlaceId:(id *)value error:(NSError **)error {
if (*value == nil)
return YES;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"placeId = %@ AND (NOT self IN %@)", *value, [NSArray arrayWithObject:self]];
NSArray *matching = fetchedWithPredicate(@"Place", self.managedObjectContext, predicate, error);
if ([matching count] > 0) {
return NO;
}
else {
return YES;
}
}
要導入數據,我從服務器獲取所有地方,以JSON格式返回。 每個地方都有自己的信息,外加一個包含父母信息的子節點,這意味着多個孩子的每個父母將多次出現。它看起來像
{ "id": 73,
"name": "Some place",
"parent": { "id": 2,
"name": "Parent's name"}
}
我想上面的代碼確實種類的「尋找或創造」,以獲取包括未保存的更改,會好的。 但它仍然嘗試爲某些地方創建多個條目(並且由於存在驗證而未能成功)。更深入地看,它確實爲同一個placeId(不同的指針)插入了不同的核心數據對象,但我不知道爲什麼。
感謝
我認爲有「setIncludesPendingChanges:YES」在我的FETCH結果足以讓在對象即使我沒有保存上下文,當前上下文也是如此。你知道這是爲什麼嗎? 除非有答案,否則你會建議使用單獨的字典。 – Nycen 2012-03-06 03:13:00
我認爲pendingChanges(在這裏猜測)可能只知道是否爲每個循環添加了定期的[[moc processPendingChanges]]調用,但如果您在主線程/運行循環中則應該定期調用它。 – 2012-03-06 13:10:07