在一个现有项目中,我尝试在项目创建很久之后引入 Core Data,因此它的模型已经到位。我已经创建了 xcdatamodel 并向其中添加了我唯一的类。该类应该充当我应用程序中对象的全局存储。该类正确实现了 NSManagedObject 并且我已经验证它是在上下文中创建和保存的,也可以通过获取结果进行检索。
在这个类中保存数据的方式是通过 NSMutableArray。但这只是行不通。这是这个类的一个片段:
@interface WZMPersistentStore : NSManagedObject<NSCoding> {
NSMutableArray *persistentStorage;
}
@property(nonatomic,retain) NSMutableArray *persistentStorage;
-(void)add:(id)element;
-(void)remove:(id)element;
-(id)objectAtIndex:(NSUInteger)index;
-(NSUInteger)num;
@end
在实现中,我还像这样覆盖 initWithEntity:
- (id)initWithEntity:(NSEntityDescription*)entity insertIntoManagedObjectContext:(NSManagedObjectContext*)context {
NSLog(@"init with entity");
[super initWithEntity:entity insertIntoManagedObjectContext:context];
return [self init];
}
init 方法仅初始化可变数组,我可以从日志中看到它在创建实体时被应用程序委托正确调用。add 方法只是将消息 insertObject 发送到persistentStorage。由此产生的问题:
- 我在“概念上”做对了吗?我的意思是,在托管对象中有实例变量并像我一样初始化是否正确?
- 当 ns 记录持久存储的大小时,即使在 addObject 消息之后记录片刻,我也总是得到 0 (编辑:这不是真的,我再次验证并且我正确地添加了 1)。
- 通过persistentStorage 存储在托管对象类中的对象是具有属性的普通类。我需要和他们做些什么吗?我想不是因为我在运行时没有收到任何错误。