How to subclass NSManagedObject class between classes?

We created a layer repository for interaction with Core Data with methods such as allItems(), addItem:(Item*)itemwhere the item is a subclass NSManagedObject. When we need to save the item, we call the method in the repository, passing the instance of the subclass as an argument. However, this does not work, because we cannot use the initializer init, and the context is hidden inside the repository.

What is the best way to transfer objects when you have such an architecture? Does the ItemDTO in passing do something like an option? Or there are better ways to solve this problem, for example, to not use NSManagedObject subclasses at all and just use a key / value that works.

+5
source share
3 answers

I wrote a copied project example that hides the context from user-defined model classes: branch 10583736 .

(this is not the final production code, just a quick example, do not expect it to run into multi-threaded or strange errors)

Hiding the context for custom classes is simply defining custom methods to solve any situation where you usually request a context and use it.

You can define a class for the storage tier without exposing the context :

@interface DataStore : NSObject

+ (id)shared;

- (void)saveAll;
- (NSEntityDescription *)entityNamed:(NSString *)name;
/* more custom methods ... */
- (NSManagedObject *)fetchEntity:(NSEntityDescription *)entity withPredicate:(NSPredicate *)predicate;

@end

, . , DataStore. .

@interface DataObject : NSManagedObject

+ (NSString *)entityName;
+ (NSEntityDescription *)entity;
- (void)save;
/* more custom methods ... */

@end

, , , , , :

@interface Card : DataObject

@property (nonatomic, retain) NSString * question;
@property (nonatomic, retain) NSString * answer;
@property (nonatomic, retain) Deck *deck;

/* return a new card */
+ (Card *)card; 

/* more custom methods ... */

@end

- , .

+1

, . ( ), . , " " , , , , .

  • , .
  • . .

, , .

+5

, , , NSManagedObject, NSManagedObjectContext. , .

, , , . , Core Data , , .

DTO, , . , , Core Data, ( ) NSManagedObjectContext .

Remember, this NSManagedObjectContextis the persistence abstraction layer, and you can back up other storage implementations if you want, including custom ones .

+3
source

All Articles