我怎样才能在Core Data中更容易保存NSSet?

时间:2012-05-03 08:40:19

标签: ios xcode core-data

我有30个房间,每个房间应该有5个相同的RoomAttributes。

我和RoomAttributes之间有很多关系。

我的解决方案是,创建30 * 5 = 150个RoomAttributes并为每个房间制作NSSet的RoomAttributes。这是分配工作。

我如何创建一个房间:

Raum *raum = [NSEntityDescription insertNewObjectForEntityForName:@"Raum" inManagedObjectContext:context];

raum.raumName = @"Main";
raum.etage = @"2. Stock, Raum 1.203";
raum.beschreibung = @"Gut beleuchtet";
raum.raumpreis = [NSNumber numberWithDouble:210];
raum.raumname = @"Besprechungsraum";

我如何创建RoomAttributes:

Raumattribute *attribute =[NSEntityDescription insertNewObjectForEntityForName:@"Raumattribute" inManagedObjectContext:context];
    attribute.attributname = @"Beamer";
    attribute.schalter = [NSNumber numberWithBool:NO];

    Raumattribute *attribute2 =[NSEntityDescription insertNewObjectForEntityForName:@"Raumattribute" inManagedObjectContext:context];
    attribute2.attributname = @"Behindertengerecht";
    attribute2.schalter = [NSNumber numberWithBool:NO];

我如何创建NSSet:

NSSet *attributeFurRaum = [NSSet setWithObjects:attribute1, attribute2,nil];  
raum.raumattribute = attributeFurRaum;

如何让这更容易?

1 个答案:

答案 0 :(得分:2)

** EDITED

啊,我明白了 - 抱歉,我误解了原来的问题 - 编辑让它更容易。

为此我会创建三个辅助方法

-(RaumAttribute*)roomAttributeWithName:(NSString *)name andSchalter:(BOOL)schalter
{
    Raumattribute *att =[NSEntityDescription insertNewObjectForEntityForName:@"Raumattribute" inManagedObjectContext:context];
    att.attributname = name;
    att.schalter = schalter;
    return att;
}

-(NSSet *)roomAttributes
{
    NSArray *atts = [@"Beamer,Behindertengerecht" componentsSeparatedByString:@","];
    NSMutableSet *roomAttributes = [NSMutableSet set];
    for(NSString *name in atts)
    {
        [roomAttributes addObject:[self roomAttributeWithName:name andSchalter:NO]];
    }
    return roomAttributes;
}

-(Raum *)raumFromDictionary:(NSDictionary *)details
{
    Raum *raum = [NSEntityDescription insertNewObjectForEntityForName:@"Raum" inManagedObjectContext:context];
    raum.raumName = [details valueForKey:@"raumName"];
    raum.etage = [details valueForKey:@"etage"];
    raum.beschreibung = [details valueForKey:@"beschreibung"];
    raum.raumpreis = [details objectForKey:@"raumpreis"];
    raum.raumname = [details objectForKey:@"raumname"];
    return raum;
}

然后您可以将预先确定的对象数据存储在plist或JSON中 - 将其解析为字典,然后执行以下操作:

NSArray *raumDictionaries = //code to get array of dictionaries from a plist or whatever  source
NSSet *raumAttributeSet = [self roomAttributes];
for(NSDictionary *raumDict in raumDictionaries)
{
    Raum *raum = [self raumFromDictionary:raumDict];
    raum.raumattribute = raumAttributeSet;
    //save context
}