Woodster
Woodster

Reputation: 3461

Extend CoreDataGeneratedAccessors Behaviour

I have a NSManagedObject subclass with CoreDataGeneratedAccessors as follows:

- (void)addCoursesObject:(Course *)value;
- (void)removeCoursesObject:(Course *)value;
- (void)addCourses:(NSSet *)value;
- (void)removeCourses:(NSSet *)value;

When objects are added or removed using the accessors above, I need some other code to run.

I effectively want to do something like this, in the implementation file:

-(void)addCoursesObject:(Course *)value {
    [super addCoursesObject:value];
     … my additional code here … }

But super doesn't make sense because NSManagedObject doesn't have "-addCourseObject". Adding an observer on the Courses NSSet seems like perhaps one approach, but I'd rather just implement my own accessor and then define how it works, much like when @synthesized accessors are implemented to go above and beyond the default behaviour.

IS there a way to invoke the original behaviour, akin to the '[super...' line above?

Thoughts? Other approaches?

Thanks.

Upvotes: 2

Views: 1633

Answers (2)

Symmetric
Symmetric

Reputation: 4031

The copy to clipboard feature seems to be gone in Xcode 4. Another way is to go the code snippet library (View/Utilities/Code Snippet Library) and drag one of the "Core Data xxx Accessors" into your .m file. You'll get methods like this:

- (void)add<#Capitalized relationship name#>Object:(<#Relationship destination class#> *)value {    
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"<#Relationship name#>" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"<#Relationship name#>"] addObject:value];
    [self didChangeValueForKey:@"<#Relationship name#>" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

and you need to replace <#Capitalized relationship name#>, <#Relationship destination class#> and <#Relationship name#>, then add your custom code. (I also had to remove [changedObjects release] since I'm using ARC.)

Upvotes: 7

TechZen
TechZen

Reputation: 64428

You can't override accessors, you just have to write you own in the .m file.

In the data model editor, if you select a relationship, you can select "Copy Objective-C 2.0 Implementation to the Clipboard" from the contextual menu. That will give you the functional skeleton of the accessors. You can then easily customize them.

Upvotes: 4

Related Questions