我得到了一些將數據從RSS源中保存到核心數據庫的代碼。它從數據創建一個對象。代碼應該檢查該項是否已經在數據庫中。但有時它似乎並不奏效。它有時會獲取1個項目的兩倍。我不確定它出錯的地方。核心數據中的雙記錄
+(NieuwsItem *)NewNieuwsItemWithData:(NSMutableDictionary *)data withContext:(NSManagedObjectContext *)context {
//Method for the creating of an new NieuwsItem object
NieuwsItem *item = nil;
//Create an fetch request to see if item allready is there
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//Set the discriptions for the FetchRequest
request.entity = [NSEntityDescription entityForName:@"NieuwsItem" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"id = %@", [data objectForKey:@"id"]];
//Catch the error
NSError *error = nil;
//Excecute the request
item = [[context executeFetchRequest:request error:&error] lastObject];
//If there are no errors and the item is not yet in the database
if (!error && !item) {
NSLog(@"Nieuw item aangemaakt met id");
//Create new agenda item
item = [NSEntityDescription insertNewObjectForEntityForName:@"NieuwsItem" inManagedObjectContext:context];
//Create an new date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *datum = [dateFormat dateFromString:[data objectForKey:@"pubDate"]];
//And set the item data
item.naam = [data objectForKey:@"title"];
item.id = [NSNumber numberWithInt:[[data objectForKey:@"id"] intValue]];
item.text = [data objectForKey:@"description"];
item.tumbURL = [data objectForKey:@"tumbafbeelding"];
item.link = [data objectForKey:@"link"];
item.datum = datum;
//Clean
[dateFormat release];
//Save the item to the context
[context save:nil];
}
//Clean up
[error release];
//Return the item
return item;
}
謝謝你的回答。我試過這個代碼,但它還沒有完成。當它更新數據庫時,它檢查對象。第一個查詢結果總是在數據庫中有0個對象。這很奇怪。 – Dawid
你願意再次發送郵件嗎?比我可以發送它。提前致謝。 – Dawid
確定收到你的郵件,你現在可以刪除它:)我會嘗試一些事情後發送它。提前致謝。 – Dawid