简体   繁体   English

核心数据模型对象保存的最佳实践

[英]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. 我需要通过核心数据将其存储在sqlite中。 I want to know what is the best approach should i bind the save method with NSmanagedobject or write differently in utility or manager? 我想知道最好的方法是将save方法与NSmanagedobject绑定,还是在实用程序或管理器中编写不同的方法?

**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*). 在“ NSManagedObject”子类(类别或其他地方*)中具有创建方法是完全可以的。

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. DataManager类中创建实体也是一种可行且非常常见的模式。 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. *) 我不再使用类别,因为很少会通过多个字段来更改模型-我更喜欢手动编辑它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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