AJ.
AJ.

Reputation: 11240

iOS core data one to many relationship NSSET

I am just wondering if it is possible to use a custom class instead of NSSET for one to many relationships in core data?

For example lets say we have:

@interface Company : NSManagedObject

@property (nonatomic, retain) NSString *companyId;
@property (nonatomic, retain) NSString *companyName;
@property (nonatomic, retain) NSSET *employees;

@end

I would like to create a class called employees like:

@interface Employees : NSSet

- (void) someCustomMethod;

@end

and then change the declaration of employees in Company to

@property (nonatomic, retain) Employees *employees;

While it builds successfully it raises an exception when I try to access someCustomMethod of Employees. Probably because the object has been created as NSSET and not as Employees.

So my questions is, can I do this and if so how do I get employees to be created as Employees and not NSSET.

Thanks,

AJ

Upvotes: 2

Views: 450

Answers (1)

Martin R
Martin R

Reputation: 539745

I do not think that is possible. The Core Data accessor methods are dynamically generated at runtime, and NSSet is used to represent a to-many relationship.

Note also that the NSSet documentation discourages you from subclassing:

There should be little need of subclassing. If you need to customize behavior, it is often better to consider composition instead of subclassing.

and later:

If the behavior you want to add supplements that of the existing class, you could write a category on NSSet. Keep in mind, however, that this category will be in effect for all instances of NSSet that you use, and this might have unintended consequences. Alternatively, you could use composition to achieve the desired behavior.

In your case, a category method on Company that operates on all the employees might be the workaround.

Upvotes: 2

Related Questions