核心数据中的自定义初始化程序和只读属性

时间:2009-11-02 14:07:33

标签: objective-c core-data

在使用Objective-C和Core Data之前,我曾经有机会创建需要使用某些参数进行初始化的类,这些参数在初始化后无法修改(尽管可以读取)。

使用Core Data,我相信我可以在我的NSManagedObject派生类上创建一个自定义init,只要它包含一种将对象插入到这样的上下文中的方法:

-(Cell*) initWithOwner:(CellList*)ownerCellList andLocation:(int)initLocation
{
    if (self = (Cell*) [NSEntityDescription insertNewObjectForEntityForName:@"Cell"
                        inManagedObjectContext:[ownerCellList managedObjectContext]])
    {
        self.location = [NSNumber numberWithInt:initLocation];
        self.owner = ownerCellList;
        [ownerCellList addCellListObject:self];
    }
    return self;
}

通常,我有一个位置变量,location属性是只读的(所以一旦初始化设置,就无法更改)。有没有办法用Core Data获得这种模式?有没有更好的方式我没想到?

谢谢!

2 个答案:

答案 0 :(得分:1)

你是对的。只要您的初始化程序调用{​​{1}}指定的初始化程序,您的方法就可以了。您还可以覆盖NSManagedObject以在插入(创建)后执行某些操作,或者-[NSManagedObject awakeFromInsert]在每次将对象故障回到托管对象上下文时执行操作(例如填充缓存)。

与Objective-C的其余部分一样,没有办法真正实现readonly属性。恶意代码可能会修改您的媒体资源。但是,在您的自定义类中,您可以声明-[NSManagedObject awakeFromFetch]例如@property(readonly)。如果您尝试修改属性并且将表明您对客户端代码的意图,这至少会引发警告。

答案 1 :(得分:0)

对于任何在这里绊倒的人,阅读评论,并在最终答案中想知道,它应该是这样的。继续上面的例子,它将是:

-(Cell*) initWithOwner:(CellList*)ownerCellList andLocation:(int)initLocation
{
    NSManagedObjectContext *context = [ownerCellList managedObjectContext];
    NSManagedObjectModel *managedObjectModel =
            [[context persistentStoreCoordinator] managedObjectModel];
    NSEntityDescription *entity =
            [[managedObjectModel entitiesByName] objectForKey:@"Cell"];
    self = [self initWithEntity:entity inManagedObjectContext:context];
    if (self)
    {
        self.location = [NSNumber numberWithInt:initLocation];
        self.owner = ownerCellList;
        [ownerCellList addCellListObject:self];
    }
    return self;
}

NSEntityDescription's insertNewObjectForEntityForName:inManagedObjectContext:文档说明这大致是从给定的entityName(@“Cell”)和上下文(从ownerCellList)转换为NSManagedObject实例的方式