【发布时间】:2013-06-23 01:39:03
【问题描述】:
我有一个 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;
}
我引用了这个问题How to remove all items and add new items to UICollectionView? 和[collectionView reloadData] 是公认的答案。
我从this 教程中选择了textFieldShouldReturn: 方法。
我还在苹果开发者库中引用了Inserting, Deleting, and Moving Section Items,但我不太确定如何实现删除项方法。
任何帮助都会很棒。这显然是一个菜鸟问题,所以代码 sn-ps 非常有用。
更新: 这是我如何让它工作的。
在上面代码中的postObject 方法和[self.collectionView reloadData] 语句之前添加了对如下所示的deleteAllEntitiesForName 方法的调用。
- (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];
}
}
【问题讨论】:
-
您的数据是否覆盖在前一个单元格上?
-
我不这么认为。就好像之前的数据被维护了,新的结果被添加到了collectionView。例如,当应用程序最初加载时,有 10 个单独的单元格,搜索完成后会加载 10 个原始单元格和 10 个新单元格。
-
为collectionView-cellForItemAtIndexPath放一些cellforrowindexpath的代码。
-
您需要在重新加载之前检查您的数组计数。
-
感谢 Abhishek,在我重新加载 collectionView 之前,数组计数没有被重置。你知道在我执行重新加载之前如何清除以前的数据吗?
标签: ios core-data uicollectionview reloaddata restkit-0.20