I have several NSFetchedResultsControllers throughout my app, and in every view controller, I implement the respective delegate methods. However, instead of copying these delegate methods into every class that implements an NSFetchedResultsController, I thought I would just create a class that implements these delegate methods, and set all fetched results controller’s delegate to point to that one class. Here’s what I’ve tried, which doesn’t work:
Since the delegate methods need to know which table view they are making changes to, I thought I would just create a separate delegate class for each fetched results controller, and send a pointer to the tableview for that class:
FetchedResultsDelegate *delegate = [[FetchedResultsDelegate alloc] initWithTableView:parentTableView];
self.fetchedResultsController.delegate=delegate;
[delegate release];
However, this causes a BAD_ACCESS crash, so this means that I probably shouldn’t be doing what I’m doing above.
How can I create a single delegate class that handles all delegate requests for all my NSFetchedResultsControllers?
Edit: I was able to fix the problem by doing @property (nonatomic, retain) FetchedResultsDelegate *delegate; Is this ok? Some people are saying something about assign rather than retain?
Nothing is retaining your
FetchedResultsDelegateas delegate properties are normally declared as assign. e.g. NSFetchedResultsController declares the delegate asTherefore you created the object and destroyed it straight away, but gave the fetchedResultsController a nasty dangling pointer.
To fix this you need a retain on the delegate. So in your UITableViewController class add a new property
then when you hook up you delegate just change your code to this
Don’t forget
Release this new ivar in the dealloc
The use of assign is all about ownership semantics.
In this case your
UITableViewControllershould own the tableView’s delegate (e.g.strong/retain) as nothing else is.The reason that the
NSFetchedResultsControllerusesassignand notretain/strongis because there is a good chance that the object that created it would act as the delegate, which would result in both objects owning each other (both having aretainheld on each other), which causes a retain cycle