1

答えが見つからない本当に簡単な質問。Core Dataエンティティをサブクラス化AreaGPSており、JSONファイルのデータを使用してそれらを設定しています。それは問題ないようです。しかし、新しく作成された2つのエンティティオブジェクト間の関係を設定するにはどうすればよいですか?

    NSManagedObjectContext *context = [self managedObjectContext];
    Area *area = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Area"
                                  inManagedObjectContext:context];

    GPS *gps = [NSEntityDescription
                                 insertNewObjectForEntityForName:@"GPS"
                                 inManagedObjectContext:context];

    NSDictionary *attributes = [[area entity] attributesByName];

    for (NSString *attribute in attributes) {
        for (NSDictionary * tempDict in jsonDict) {  
            id value = [tempDict objectForKey:attribute];

            if ([value isEqual:[NSNull null]]) {
                continue;
            }

            if ([attribute isEqualToString:@"latitude"] || [attribute isEqualToString:@"longtitude"]) {
                [gps setValue:value forKey:attribute];
            }
            else {
                [area setValue:value forKey:attribute];
            }
        }

        [area setAreaGPS:gps]; // Set up the relationship
        }

Areaからの関係の名前GPSareaGPS

エラー:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "areaGPS"; desired type = NSSet; given type = GPS; value = <GPS: 0x369540>

私は[area setAreaGPS:gps];いくつかの例でこの構文を見てきましたが、どうやらそれを正しく使用する方法を理解していないようです。

4

1 に答える 1

3

関係を対多関係として設定しました。領域をどのように定義するかによって、これが適切な選択である場合とそうでない場合があります。1 つの領域に複数の GPS オブジェクトを関連付けることができれば問題ありません。変更する必要があるのは、次のことだけです[area setAreaGPS:gps]

NSMutableSet *mutableGPS = [area.areaGPS mutableCopy];
[mutableGPS addObject:gps];
[area setAreaGPS:mutableGPS];

Area オブジェクトに関連付けられた GPS オブジェクトが 1 つだけ必要な場合は、関係を対多の関係ではなく、対 1 の関係に変更する必要があります。その場合、コードを変更する必要はありません (NSManagedObjectサブクラスの再生成を除く)。

于 2013-01-13T23:25:55.560 に答える