2015-11-01 64 views
3

我有2個實體:目標和類別。我向目標實體添加了關係「類別」。我希望該用戶可以從列表中選擇一個類別,然後將該類別添加爲與目標對象的關係。但是,我得到錯誤:-[__NSSingleObjectSetI managedObjectContext]: unrecognized selector sent to instance 0x138a22fa0無法將關係對象設置爲CoreData中的另一個對象

我的代碼:

- (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也許這某種愚蠢的問題,但我跟很多資源的開發,並不能找到什麼是問題。

回答

5

如果你的Goal對象只能有一個類別,那麼它是一對一的關係,這意味着category屬性是一個對象,而不是一組對象(甚至不是一組1對象)。

你應該設置你的類別,象這樣:

[goal setValue:objCategory forKey:@"category"]; 
相關問題