I’m working on an app where I have two very similar model classes. I want to use both of these classes in one view controller, which layout is based on properties from the model classes. The problem is that I currently have a lot of if statements to check which class it is.
Example:
- (UIView *)setUpViewForObject:(id)object
{
// Check if it is a Post or Event object
Post *post;
Event *event;
if ([object class] == [Event class]) {
event = (id)object;
} else if ([object class] == [Post class]) {
post = (id)object;
}
if (post) {
// Do stuff
// ie:
self.customUiView.textField.text = post.text;
} else if (event) {
// Do similar stuff
// ie:
self.customUiView.textField.text = event.text;
}
}
This solution seems pretty redundant, and I do it in a couple of places. I therefore wonder if it is possible to create a wrapper class of two NSManagedObject classes. I use CoreData and have generated the models from xCode so I wouldn’t use all these if statements.
Something like:
@interface News : NSManagedObject
[...]
@property (nonatomic, retain) NSString * text;
[...]
@interface Event : NSManagedObject
[...]
@property (nonatomic, retain) NSString * text;
[...]
Is it possible to create a wrapper class of these two NSManagedObject classes, maybe with enums. I also would like the objects to be updatable, deletable etc. Was thinking that I maybe could use Enum or something similar to create an abstract class, but I don’t know how a class like that would look, work and be used.
Any suggestions if this is possible and in that case how a wrapper class like this would look would be greatly appreciated.
Core Data supports the concept of an abstract superclass. So you define that with one property, say “tag”, that differentiates the two classes. Then News and Event both have that class as their superclass. This is a very common type of solution used with Core Data.