2013-10-02 33 views
0

我在CoreData模型“Valla”和“Dagbok”中有两个实体,这些实体与多对多关系相关。核心数据添加与fetchRequest结果相关的新实体文章

当我向Dagbok实体添加一个新帖子时,我希望它与来自Valde实体的帖子相关联,该实体存储在FetchRequest的NSArray中。

的代码,现在只是增加了一个帖子Dagbok

- (void)initDagbokDBWithText:(NSString *)text header:(NSString *)header degree:(int)degree weather:(NSString *)weather farg:(NSString *)farg 
{ 
    AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate]; 
    context = [appdelegate managedObjectContext]; 

    NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Dagbok" inManagedObjectContext:context]; 
    NSManagedObject *newDagbok = [[NSManagedObject alloc] initWithEntity:entitydesc insertIntoManagedObjectContext:context]; 

    //NSRelationshipDescription *dagbokRelation = [[NSRelationshipDescription alloc] init]; 
    //NSRelationshipDescription *vallaRelation = [[NSRelationshipDescription alloc] init]; 

    [newDagbok setValue:text forKey:@"text"]; 
    [newDagbok setValue:header forKey:@"header"]; 
    [newDagbok setValue:[NSNumber numberWithInt:degree] forKey:@"degree"]; 
    [newDagbok setValue:weather forKey:@"weather"]; 
    [newDagbok setValue:farg forKey:@"colorCode"]; 

    NSError *error; 
    if(![context save:&error]) 
    { 
     NSLog(@"Whoops : %@", [error localizedDescription]); 
    } 

} 

如何从与fetchRequest结果阵列添加相关的对象?

回答

0

如果您创建NSManagedObject子类来表示您的实体,而不是直接处理NSManagedObject,生活将会更容易。通过在模型中为您的类添加一个名称(实体的“类”属性),例如为Valla设置VallaEntity。然后XCode可以自动生成这些类,这些类将具有用于简化代码的属性和方法,例如

DagbokEntity *newDagbok = [[NSManagedObject alloc] initWithEntity:entitydesc insertIntoManagedObjectContext:context]; 

newDagbok.text = text; 
newDagbok.header = header; 
newDagbok.degree = [NSNumber numberWithInt:degree]; 
newDagbok.weather = weather; 
newDagbok.colorCode = farg; 
[newDagbok addVallas:[NSSet setWithArray:arrayOfRelatedVallas]];