Assignment #4 Task #11

Please note, this blog entry is from a previous course. You might want to check out the current one.

The list of recents photos should be saved in NSUserDefaults. The arrays you get back from the FlickrFetcher methods are all property lists.

Inside the photo view controller we set the setter for the photo model to save its data to NSUserDefaults. First we copy the existing list, or create an empty array if there is no entry yet. Using a block enumerator we loop through the array to see if the current photo is already there and remove it. Then we add the current photo data to the beginning of the array. If the array exceeds 20 items we delete the last one.

- (void)setPhoto:(NSDictionary *)photo
{    
    if (_photo == photo) return;
    _photo = photo;        
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *recents = [[defaults objectForKey:RECENTS_PHOTOS_KEY] 
                               mutableCopy];
    if (!recents) recents = [NSMutableArray array];
    NSUInteger key = [recents indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [[photo objectForKey:FLICKR_PHOTO_ID] 
                isEqualToString:[obj objectForKey:FLICKR_PHOTO_ID]];
    }];
    if (key != NSNotFound) [recents removeObjectAtIndex:key];    
    [recents insertObject:photo atIndex:0];
    if ([recents count] > NUMBER_OF_RECENT_PHOTOS) 
        [recents removeLastObject];    
    [defaults setObject:recents forKey:RECENTS_PHOTOS_KEY];
    [defaults synchronize];    
}

Next we populate the model of the recent-photos table view controller:

- (void)viewWillAppear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.photos = [[defaults objectForKey:RECENTS_PHOTOS_KEY] copy];     
}

Finally we want to view a selected photo. Thus we embed the recent-photos table view controller in story board inside a navigation view controller, create a segue from its cell to the photo view controller and prepare the segue:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [super prepareForSegue:segue sender:sender];
    if ([segue.identifier isEqualToString:@"Show Photo"]) {
        [segue.destinationViewController setPhoto:
         [self.photos objectAtIndex:
          [self.tableView indexPathForSelectedRow].row]];        
    }
}

The complete code for this task is available at github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.