Adding a decorator to a class derived from NSManagedObject

I would like to add additional behavior to a class derived from NSManagedObject and there are 4 different (truly) behavior groups. I don't need my decorator class to persist with CoreData - it's purely for adding runtime behavior.

However, if I try to apply the standard Decorator pattern, I cannot name '[super init]', which makes sense because you need to insert a new object into the ManageObjectContext. But I thought you would want to call [super init] in initClassScrollDecorator init and similarly, later on "dealloc", so that everything is properly initialized and cleaned up.

I inherit the class 'MyWindowClass' because I don't want my client classes to know the subtype, but depending on the decorator used, the behavior will be different.

So what's a good way to approach this?

@interface MyWindowClass :  NSManagedObject  
{
}
@end

@interface WindowClassScrollDecorator: MyWindowClass
{
   MyWindowClass    *decoratedClass;
}

- (id)initWithMyWindowClass:(MyWindowClass *)aWindowClass;

@end

@implementation WindowClassScrollDecorator

- (id)initWithMyWindowClass:(MyWindowClass *)aWindowClass
{
    // Calling [super init] elicits the following error:
    // Failed to call designated initializer on NSManagedObject class 'ModelClassScrollDecorator' 
    if (self = [super init])    
    {
        // do some initialization work here
        self.decoratedClass = aWindowClass;
    }
}

@end

      

+2


source to share


2 answers


The life cycle is NSManagedObject

slightly different from the life cycle of other objects; in particular, an object can become an error (essentially a wrapper object without any of its properties) without being freed. You need to be sure you are aware of these events, so you can look at NSManagedObject Reference - Notes Subclasses . In particular, you can look at awakeFromInsert:

, awakeFromFetch:

and (will|did)TurnIntoFault

.

To eliminate your immediate problem, NSManagedObject

you cannot be created without NSManagedObjectContext

one to live. Thus, to initialize a managed object, you must call its designated initializer:



initWithEntity:insertIntoManagedObjectContext:

      

Your init method must call this method in the superclass, otherwise yours NSManagedObject

won't work.

+1


source


The question you have here seems to be not CoreData specific, but OO design.

You shouldn't inherit from NSManagedObject if it's not NSManagedObject.



You have to make MyWindowClass either a protocol or a class that has an NSManagedObject.

0


source







All Articles