Workaround for @synthesize when changing access methods in subclasses

I have several UITableViewControllers and want all of them to have several properties, such as fetchedResultsController and managedObjectContext. Therefore, I made an abstract class for all of them, to add these common properties once, as well as to execute some protocols (for example, others that I come across) and change / add code for all these similar TVCs. I defined a property called fetchedResultsController in the title of this abstract class:

@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;

In each subclass of my abstract class, I want to create a custom getter for this property, to lazily create an instance of fetchedResultsController and initialize a select request, etc. I found that I need to add:

@synthesize fetchedResultsController = _fetchedResultsController;

Each subclass must have iVar to create a recipient.

My question is:

Why can't I see iVars properties in each of my subclasses of my abstract class?

Or in other words:

Is there a way to make custom accessor methods for a property defined in a superclass without the need for @synthesize iVar?

+4
source share
2 answers

Ivarians are private to a class that defines a property (and synthesizes ivar). Subclasses do not have access to the private ivars of their parent classes. This is a good thing.

Why don't you do something similar in your subclass (instead of every subclass call @synthesize):

Subclass.m

- (NSFetchedResultsController *)fetchedResultsController {
    NSFetchedResultsController *result = [super fetchedResultsController];
    if (!result) {
        result = ... // lazy load your controller
        [super setFetchedResultsController:result];
    }

    return result;
}

, ivar .

, self super setFetchedResultsController:.

+2

, iVar , . .

@interface BaseTableViewController : UITableViewController
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
- (BOOL)isFetchedResultsControllerLoaded;
- (NSFetchedResultsController *)createFetchedResultsController;
@end

@implementation BaseTableViewController

- (BOOL)isFetchedResultsControllerLoaded
{
    return (_fetchedResultsController!=nil);
}

- (NSFetchedResultsController *)createFetchedResultsController
{
    [self doesNotRecognizeSelector:_cmd];
    return nil;  // To please the static analyzer
}

- (NSFetchedResultsController *)fetchedResultsController
{
    if (!_fetchedResultsController) {
        _fetchedResultsController = [self createFetchedResultsController];
        NSAssert(_fetchedResultsController!=nil, @"Creating Fetched Results Controller failed.");
        // Do any common initialization, like setting a delegate
    }
    return _fetchedResultsController;
}

@end

-createFetchedResultsController.

0

All Articles