Goal c is to create NSManagedObject and regular NSObject classes that inherit from the same parent class

In my iPhone application, I have two view modes: viewController1 has a tableView that shows a list of Item1 objects viewController2 has a tableView that shows a list of Item2 objects

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

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

But I do not want Item1 to be NSManagedObject, I want to use it as a regular object.

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

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

+4
source share
1 answer

You most likely need an interface that this class can implement. I will use a human example:

@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 

Inheriting a class from NSManagedObject

 @interface ManagedPerson : NSManagedObject <PersonInterface> @end @implementation ManagedPerson @dynamic firstName; @dynamic lastName; @end 

Now, if an object should use any of these classes, it doesn’t matter that it supertypes it, it doesn’t matter that the object answers -firstName , -lastName , -setFirstName or -setLastName .

To provide this flexibility, you need to make sure that the objects you want to use match the interface, since you no longer worry about a particular type, for example:

 @interface FootballClub : NSObject @property (nonatomic, retain) id<PersonInterface> clubManager; // .. other properties @end 

Refresh

To get a general implementation, you can consider composition / delegation.

Structure

You create another class that encapsulates the overall work, and then uses it as accessible as ivar for use in your class.

Delegation

Do the same as other common elements, such as a UITableView . At certain points, it calls a datasource (any element that implements the necessary <UITableViewDatasource> methods) to ask it to do something. Then you have two objects that use the same class as the data source, and the implementation will be split.

+9
source

Source: https://habr.com/ru/post/1391097/


All Articles