我有一个NSManagedObject
类,其字段类型为NSMutableArray
,但当我调用[self.managedObjectContext save:&error];
时,NSMutableArray
字段并未保存更改。
其他字段,如NSString
按预期保存。
如何将NSMutableArray
保存到Core Data存储中,或者有其他方法可以执行此操作吗?
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CatelogsList : NSManagedObject
@property (nonatomic, retain) NSMutableArray* list;
@end
- (IBAction)addCatelog
{
NSString* nextname=self.catelogText.text;
Catelog* newCatelog=[[Catelog alloc] init];
newCatelog.name=nextname;
newCatelog.texts=[[NSMutableArray alloc] initWithCapacity:20];
[list addObject:newCatelog];
//where list is the reference of the 'list' field in the NSManagedObject class above
[self.managedObjectContext save:nil];
NSLog(@"saved");
}
列表没有保存任何更改,每当我重新启动程序时,列表的大小都会回到0
答案 0 :(得分:1)
不要只将自己的属性添加到托管对象类。将属性添加到模型中并将其类型设置为transformable
。默认情况下,它使用归档程序将数组写入数据存储区。
您显式添加到托管对象子类的属性不受数据存储的支持,永远不会保存。
答案 1 :(得分:0)
首先构建数据模型,然后以这种方式添加所需的属性,save方法会将它们写入持久存储。
据我了解,永远不会保存不属于托管对象模型的添加属性。
答案 2 :(得分:0)
如果要将自定义类存储到SQLite数据库中,则需要为自定义类定义两种方法:(void)encodeWithCoder:(NSCoder)coder;
和-(id)decodeWithCoder:(NSCoder*)decoder;