无法将关系对象设置为CoreData中的另一个对象

时间:2015-11-01 16:43:58

标签: ios objective-c core-data

我有2个实体:目标和类别。我向目标实体添加了关系“类别”。我希望该用户可以从列表中选择一个类别,然后将该类别添加为与Goal对象的关系。但我收到错误:-[__NSSingleObjectSetI managedObjectContext]: unrecognized selector sent to instance 0x138a22fa0

我的代码:

- (BOOL)save {

    // Get Category object
    NSManagedObject *objCategory = [self getCategoryObjectWithID:@"1"];
    if (!objCategory) {
        NSLog(@"ERROR objCategory fetching!");
        return;
    }

 NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Goal"
                                               inManagedObjectContext:[CoreDataWrapper myManagedContext]];

    NSManagedObject *goal = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:[CoreDataWrapper myManagedContext]];
    [goal setValue:strID forKey:@"id"];
    [goal setValue:[NSSet setWithObject:objCategory] forKey:@"category"]; // here error

return [CoreDataWrapper saveMyContext];

}

- (NSManagedObject *)getCategoryObjectWithID:(NSString *)catID {

    // Fetching
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Category"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"categoryID", catID];
    [fetchRequest setPredicate:predicate];

    // Execute Fetch Request
    NSError *fetchError = nil;
    NSArray *result = [[CoreDataWrapper myManagedContext] executeFetchRequest:fetchRequest error:&fetchError];

    if (!fetchError) {
        return result[0];
    }

    return nil;
}

我是CoreData的新手,也许这是一些愚蠢的问题,但我跟着很多资源,找不到问题。

1 个答案:

答案 0 :(得分:5)

如果您的Goal对象只能有一个类别,那么它就是一对一的关系,这意味着category属性是一个对象,而不是一组对象(甚至不是一组1个对象)。

您应该像这样设置类别:

[goal setValue:objCategory forKey:@"category"];