简体   繁体   中英

Best practice for core data model object save

I have a two entity "Person" and "Car" is coming from the web service. I need to store that in sqlite through core data. I want to know what is the best approach should i bind the save method with NSmanagedobject or write differently in utility or manager?

**Approach 1** 

@interface Person : NSManagedObject

@property (nonatomic, retain) NSString * title;

- (void) saveManagedObject:(NSDictionary*)response //Responsible for init the person object and save in context

@end

**Approach 2**

@interface CoreDataUtility : NSObject

- (void) saveManagedObject:(NSDictionary*)response //Responsible for create the person object and save in context

@end

Short answer: both methods are good, especially if you do not want to deal with 3rd party frameworks. Those might be useful, but the also bear some risks; this would be another question.

It is perfectly fine to have a creation method in the `NSManagedObject´ subclass (in a category or elsewhere*).

However, you should make it a class method, not an instance method.

To create an entity in a DataManager class is also a feasible and a very common pattern. The good thing about the utility class is that you can more easily maintain multiple contexts for background operations.

*) I do not use categories any more because it is rare to change the model by more than a few fields- I prefer to edit them manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM