重新加载CollectionView不会清除以前加载的单元格

Ben*_*Ben 5 core-data reloaddata ios uicollectionview restkit-0.20

我有一个iOS应用程序,它利用RestKit 0.20.1从Restful Web服务中检索数据.我还应该添加应用程序使用CoreData.应用程序启动时,主屏幕是一个由默认搜索词填充的集合视图.标题中还有一个用作搜索栏的文本字段.

当用户使用搜索栏时,我无法清除以前加载的单元格.它只是加载新单元格并将之前的单元格向下推.这是适用的代码.

- (BOOL) textFieldShouldReturn:(UITextField *)textField {

//This sets up the NSDictionary for the Restkit postObject parameters
    NSArray *objects =[NSArray arrayWithObjects:textField.text, nil];
    NSArray *keys =[NSArray arrayWithObjects: @"query",nil];
    NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    self.search=params;

//This is the POST request to the server
    [[RKObjectManager sharedManager] postObject:nil path:@"/rest/search?ip=255.255.255.0" parameters:search success:nil failure:nil];

//This is what I thought would clear out the old and replace with the new    
    [self.collectionView reloadData];    

    [textField resignFirstResponder];
    return YES; 
}
Run Code Online (Sandbox Code Playgroud)

我引用了这个问题如何删除所有项目并向UICollectionView添加新项目?并且[collectionView reloadData]是公认的答案.

我选择了教程中的textFieldShouldReturn:方法.我还在apple开发者库中引用了Inserting,Deleting和Moving Section Items,但我不太确定如何实现delete items方法.

任何帮助都会很棒.这显然是一个新手问题所以代码片段非常有用.

更新: 这是我如何让它工作.

在上面的代码中deleteAllEntitiesForNamepostObject方法和[self.collectionView reloadData]语句之前添加了对下面显示的方法的调用.

- (void) deleteAllEntitiesForName:(NSString*)entityName {
    NSManagedObjectContext *moc = [self managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription
    entityForName:entityName inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error = nil;
    NSArray *array = [moc executeFetchRequest:request error:&error];
    if (array != nil) {
        for(NSManagedObject *managedObject in array) {
            [moc deleteObject:managedObject];
        }
        error = nil;
        [moc save:&error];
    }

}
Run Code Online (Sandbox Code Playgroud)

我从这里得到它:正确刷新Core Data数据库的方法

arc*_*ist 3

根据UICollectionView(而不是 RestKit)的经验,您可能需要在调用reloadData. 产生这种效果的原因是,您用来确定集合视图中的项目和部分数量的源中仍然包含旧数据。

验证这一点的一个简单方法是在调用之前 NSLog 数据源的内容reloadData

希望这可以帮助!