我遇到的问题是我无法分配子类的属性,除非我将子类实体的父实体属性设置为抽象超类的实体.
在XCode 4.0.2中,这是我所指的父实体属性:
我没有得到的是,我认为父实体是用于实体之间的父子关系,对象关系只是由类定义捕获.
例
实体A,B和C:
> A是类型A的抽象实体,具有以下属性:
> y:字符串
> z:字符串
> B是A类型的实体,没有属性
> C是A类型的实体,没有属性
A,B和C类:
@interface A : NSManagedObject { } @property (nonatomic,retain) NSString * y; @property (nonatomic,retain) NSString * z; @interface B : A { } @interface C : A { }
问题
如果我没有将实体B和C的父实体设置为实体A,那么当我尝试时:
NSEntityDescription *be = [[mom entitiesByName] objectForKey:@"B"]; B *b = [[NSManagedObject alloc] initWithEntity:be insertIntoManagedObjectContext:moc]; b.y = @"test"; // <<-- This line causes the following error:
我明白了:
-[NSManagedObject setY:]: unrecognized selector sent to instance
如果我设置父实体,它似乎工作,但持有到实体的实体似乎是A而不是B.
解决方法
你还记得将实体B的类设置为B类吗?如果是,你应该看一下分配给b的指针的类型……它实际上是B *吗?看起来它可能是一个NSManagedObject *,基于你得到的错误,并根据
-initWithEntity:insertIntoManagedObjectContext:
的文档……
The dynamically-generated subclass
will be based on the class specified
by the entity,so specifying a custom
class in your model will supersede the
class passed to alloc.
…如果您的模型配置正确,我认为您应该获得B *.