Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective c - making a NSManagedObject and regular NSObject classes that inherit from the same parent class

In my iPhone app I have two viewControllers: viewController1 has a tableView that shows a list of Item1 objects viewController2 has a tableView that shows a list of Item2 objects

Where Item1 class and Item2 class inherit from the abstract class ParentItem.

Now I want to make Item2 object a NSManagedObject so I can save it on the device and make the viewController2 use a NSFetchedResultsController to load its tableView with Item2 objects.

But I don't want Item1 to be a NSManagedObject, I want to use it as regular object.

The problem is that if I create ParentItem class as NSManagedObject then Item1 class will also be a NSManagedObject and I can't use it as a regular object (I mean I wont be able to create an Item1 object with regular alloc-init, or can I???)

And if I create ParentItem class as regular NSObject, then Item2 class will also be regular NSObject.

like image 726
Eyal Avatar asked Jan 17 '23 19:01

Eyal


1 Answers

What you most likely need is an interface that the two class's can implement. I'll use the example of a person:

@protocol PersonInterface <NSObject>

@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;

@end

Class inheriting from NSObject

@interface NonManagedPerson : NSObject <PersonInterface>
@end

@implementation NonManagedPerson

@synthesize firstName = _firstName;
@synthesize lastName  = _lastName;

@end

Class inheriting from NSManagedObject

@interface ManagedPerson : NSManagedObject <PersonInterface>
@end

@implementation ManagedPerson

@dynamic firstName;
@dynamic lastName;

@end

Now if an object needs to use either of these classes it does not care what it's supertype it, it will only care that the object responds to -firstName, -lastName, -setFirstName or -setLastName.

To allow this flexibility you need to be ensuring that the objects you want to use conform to the interface as you are no longer bothered about a specific type e.g.:

@interface FootballClub : NSObject

@property (nonatomic, retain) id<PersonInterface> clubManager;

// .. other properties

@end

Update

To get shared implementation you could consider composition/delegation.

Composition

You make another class that encapsulates the common work and then have it as an available as an ivar to be used in your class.

Delegation

Do the same as other common elements, such as UITableView. At certain points it calls out to it's datasource (any element that implements the required methods of <UITableViewDatasource>) to ask for something to be done. You can then have two objects use the same class as a datasource and the implementation will be shared.

like image 168
Paul.s Avatar answered Feb 08 '23 23:02

Paul.s