开发者

How can I create a Core Data relationship from one entity to another, existing entity?

During the creation of a Core Data entity (Event)开发者_StackOverflow中文版, I am creating a relationship to another entity (Team). This relationship is many-to-one from Team to Events (one team, many events) and has an inverse relationship from Event to Team.

Team<----->>Event.

The delete rule for both relationships is set to 'Nullify'.

The below block of code works successfully on first population when a new Team is created during the creation of each Event. However, if I then remove an Event and attempt to re-add it, the existing Team is retrieved but the code fails when attempting to add the Team object to the Event in the final line of the example. The error is as follows: -[__NSCFDictionary managedObjectContext]: unrecognized selector sent to instance 0x699ed60

What is the correct way to create a relationship between the Event object to the Team object that already exists?

Team *currentTeam = self.team;
Team *newTeam = (Team *)[self loadTeamForNid:[NSNumber numberWithInteger: [teamNid integerValue]]];
// If the nid of the referenced team has changed, 
if (![[[currentTeam nid] stringValue] isEqualToString:teamNid]) {
    currentTeam = nil;
    currentTeam = newTeam;
}

// If an event has not been set by this point, it does not exist in the CD store, and we need to create it.
if (currentTeam == nil) {
    currentTeam = (Team *)[NSEntityDescription insertNewObjectForEntityForName:@"Team" inManagedObjectContext:[delegate managedObjectContext]];    
    [currentTeam populateTeamWithNode:[node nodeGet:teamNid]];
}

// TODO: This breaks on reload of an object
//    self.team = currentTeam;
[self setValue:currentTeam forKey:@"team"];


Conceptually, you aren't mistaken: you set the event's "team" property to an instance of NSManagedObject that represents the appropriate team.

This message:

-[__NSCFDictionary managedObjectContext]: unrecognized selector sent to instance 0x699ed60

Means that some line of code is handling an instance of NSDictionary where it expects (I assume) an instance of NSManagedObject. When it tries to query the object's managedObjectContext, an exception is thrown, because an NSDictionary doesn't implement a method for that selector.

The first thing to do is put a breakpoint on that last line and see if currentTeam is actually an NSDictionary in disguise. (This seems unlikely, given the code above an exception would have been hit earlier.) If not, you'll have to hunt around for related properties that might be involved in this code path.

Note that Core Data supports a fetch request style where it returns NSDictionary instances instead of NSManagedObjects; if you are using this anywhere in your code, you might be accidentally passing the result along to another method that doesn't expect it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜