Search code examples
iphoneobjective-cviewdidloadcs193p

Can i do the initialization in a method?


For example, i got a method like this:

- (void)addToRecents:(NSDictionary *)photo
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *recents = [[defaults objectForKey:@"RecentPhotos"] mutableCopy];
    if(!recents) recents = [NSMutableArray array];
    [recents addObject:photo];
    [defaults setObject:recents forKey:@"RecentPhotos"];
    [defaults synchronize];
    self.recentPhotos = [[NSUserDefaults standardUserDefaults] objectForKey:@"RecentPhotos"];    
    [self.tableView reloadData];
}

Then it always couldn't show the tableview i want. I use the nslog to print something in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath to see if this method really got called. Then i found out it never got called.


Solution

  • I did the above cause from my past experience in C or Java, i think the place where you do the setup or initialization doesn't matter, as long as you just do it anywhere you want even in a method or function like these lines:

    self.recentPhotos = [[NSUserDefaults standardUserDefaults] objectForKey:@"RecentPhotos"];    
    [self.tableView reloadData];
    

    However it didn't work at all. It took me about one hour to check every other stuff to figure it out cause i always thought i'm doing the right way like in Java.

    Then i tried to put them inside the viewDidLoad(), it worked. I watched the Stanford lectures about viewController lifecycle again and as Paul said: it's better to do all the setup or initialization in the vieDidLoad(). Now I learn this difference.

    This is just my own experience from working on the assignment 4.

    Hope it would help others not waste too much time on this. Thanks