PDA

View Full Version : Changing a ManagedObject's relationship?




Littleodie914
Aug 2, 2007, 10:36 PM
Hi guys, I seem to be having relationship issues... :rolleyes:

I've got a Subject entity, which holds lots of Task entities. I want to change one Task entity's "parentSubject" relationship to something else.

So, lets say I've got two subjects, with "title" keys "Bio" and "Chem."

I have the task object, and I have the ability to change the relationship using:

[myObject setValue:subjectObject forKey:@"parentSubject"];

Problem is, I can't figure out how to obtain the "subjectObject." I have the string of its "title" key, and I have the list of Subject MO's using:

[subjectController arrangedObjects]

But, how do I search that returned NSArray for a certain title string? I've been running through loops of "valueForKey:" and NSEntityDescription's, and I can't make heads or tails of the hierarchy. I'm sure there's an easy, simple way to do this, but I've yet to stumble upon it. :(



Littleodie914
Aug 2, 2007, 10:46 PM
Ah, I seem to have found my own answer. :)

Using NSFetchRequest:

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Subject" inManagedObjectContext:context];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Bio"]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [context executeFetchRequest:request error:&error];

NSManagedObject *subjectObject = [array objectAtIndex:0];

The above will return the ManagedObject with the title "Bio." Hope this helps anyone with a similar issue. ;)