I have an IOS app that is using RestKit to pull json formatted data from a server into a CoreData Entity. Some of the attributes of the entity help populate a collection view with an image and title for each cell.
I am attempting to move from the collection view to a detail view when a cell is selected. There is a "summary" attribute of the CoreData Entity that I would like to display in the detail view along with the image.
I know I can pass data thru the prepareForSegue
method. But I am not sure how to specify the image and summary data I want to pass.
Maybe passing the image and summary is not the proper way? Should I be passing the managedObjectContext
to the detail view controller and fetching the results from there?
Here is how my CollectionView is populated.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
MyNewsCollectionViewCell *cell = (MyNewsCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSURL *photoURL = [NSURL URLWithString:(NSString *) [object valueForKey:@"imageUrl"]];
NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
[cell.cellimg setImage:[[UIImage alloc] initWithData:photoData]];
[cell.title setText:[object valueForKey:@"title"]];
return cell;
Here is the prepareForSegue
method
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"newsDetail"]) {
NewsDetailViewController *vc =[segue destinationViewController];
vc.newsDetailImageView = //How do I designate the image from the cell I selected???
vc.newsDetailText = //How do I designate the text from the cell I selected???
}
}
This is obviously a beginners question.... any help would be much appreciated. Given that I'm a beginner basic example code really helps!
If the cell selection triggers the segue instantly, you can make use of the indexPathForSelectedItems
method of UICollectionView
to get the indexPath
that you need to get your NSManagedObject
.
Try this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"newsDetail"]) {
NewsDetailViewController *vc =[segue destinationViewController];
// In the following line, replace self.collectionView with your UICollectionView
NSIndexPath *indexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSURL *photoURL = [NSURL URLWithString:(NSString *)[object valueForKey:@"imageUrl"]];
NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
UIImage *img = [[UIImage alloc] initWithData:photoData];
vc.newsDetailImageView = [[UIImageView alloc] initWithImage:img];
vc.newsDetailText = howeverYouGetYourObjectSummary;
}
}