Двойные записи в основных данных - PullRequest
0 голосов
/ 28 ноября 2011

Я получил некоторый код, который сохраняет данные из 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;
}

Ответы [ 2 ]

0 голосов
/ 28 ноября 2011

Я не уверен, что запрос на выборку выдаст ошибку, если отсутствует объект с идентификатором.Вы можете рассмотреть возможность использования счетчика объекта.Поэтому, заменив

//Excecute the request item = [[context executeFetchRequest:request error:&error] lastObject];

на

NSInteger countForFetchRequest = [context countForFetchRequest:fetchRequest error:&error];

Если countForFetchRequest равно нулю, то вы можете вставить объект (объект с заданным значениемid) как новый объект.

0 голосов
/ 28 ноября 2011

Попробуйте использовать этот код:

...

//Catch the error
NSError *error = nil;

[request setFetchLimit:1]; //You shouldn't make a search for more than 1 element, so limit the fetch.

NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] 
                                                         initWithFetchRequest:request 
                                                         managedObjectContext:context
                                                         sectionNameKeyPath:nil cacheName:nil];
[fetchedResultsController performFetch:&error];
if (error) {
    // do something
    return nil;
}
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:0];
if ([sectionInfo numberOfObjects] > 0) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    item = [[fetchedResultsController sections] objectAtIndexPath:indexPath];
}
//If there are no errors and the item is not yet in the database
if (!item) {
    ...
}
//Clean up 
[fetchedResultsController release];

//Return the item
return item;
...