meow
meow

Reputation: 28174

Making a function that repeats across view controllers DRY

I have a function that i use across my view controllers. Where is the best place to put this such that i do not repeat this across these controllers?

-(void)addNewQuestion
{
    AddNewQuestionViewController *anqvc = [[AddNewQuestionViewController alloc]initWithTopic:self.topic];

    [anqvc setCompletionHandler:^(Question *newQuestion){
        [self.questionTableView reloadData];
    }];

    [self.navigationController pushViewController:anqvc animated:YES];
    [anqvc release];
}

Upvotes: 2

Views: 73

Answers (2)

thomas
thomas

Reputation: 5649

you should implement the observer-pattern.

somewhere in your app you have the model: your questions and each ViewController whoch need lists all questions should observe that list in your model. If something changes in your model: for instance adding a new question, all observers will be notified.

In obj-c you can use Key-Value-Observing for that.

So each VC which lists your data in a tableview you can call [self.tableView reloadData]

Or even better: create a new class which only implements the DataSource and use in all tableViews the same DataSource.

Upvotes: 1

Jonah
Jonah

Reputation: 17958

If you have a bunch of classes with common same state (a questionTableView) and behavior (addNewQuestion) that sounds like a great time to introduce a common base class for them to all inherit from.

Upvotes: 1

Related Questions