I have an iOS app that utilizes RestKit 0.20.1 to retrieve data from a Restful web service. I should also add the app uses CoreData. When the app is started the main screen is a collection view that is populated by a default search term. There is also a textfield in the header that is used as a search bar.
I am having trouble clearing out the previously loaded cells when the user uses the search bar. It just loads the new cells and pushes the previous ones down. Here is the applicable code.
- (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;
}
I referenced this question How to remove all items and add new items to UICollectionView? and [collectionView reloadData]
was the accepted answer.
I chose the textFieldShouldReturn:
method from this tutorial.
I have also referenced Inserting, Deleting, and Moving Section Items in the apple developer library but I'm not quite sure how to implement the delete items methods.
Any help would be great. This is clearly a rookie question so code snippets are VERY helpful.
UPDATE: Here is how I got it to work.
Added a call to the deleteAllEntitiesForName
method shown below before the postObject
method and [self.collectionView reloadData]
statements in the code above.
- (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];
}
}
I got it from here: Correct way to refresh Core Data database
From experience with UICollectionView
(not with RestKit), you probably need to clear out your data source before calling reloadData
. The reason you're having this effect is that the source that you use to determine the number of items and sections in the collection view still has old data in it.
A simple way to verify this is to NSLog the contents of the data source just before calling reloadData
.
Hope this helps!