我得到了一些将数据从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