开发者

What's the Relationship Between Fetch and One Way Relationship in Core Data?

开发者 https://www.devze.com 2023-02-25 05:54 出处:网络
Why \"Fetch\" means one way relationship开发者_JS百科 What is the relation between fetch and one way?Well, I\'m not sure I understand your question, but I\'ll try and answer in the context of a simpl

Why "Fetch" means one way relationship

开发者_JS百科

What is the relation between fetch and one way?


Well, I'm not sure I understand your question, but I'll try and answer in the context of a simple domain model.

Let's say you have a Person class and a Computer class, both extend NSManagedObject. Person is linked to Computer via a one-way relationship, a NSSet named computers.

This would allow you to say in your code:

Person *person = // ... (loaded from database)
NSSet *computers = person.computers;
for (Computer *computer : computers) {
   // do something fun
}

However, since it's a one-way relationship, you would not be able to do this:

Computer *computer = // loaded from DB
Person *person = computer.person;  // This line won't work

Therefore, since it won't work -- there's no backwards relationship -- the only way to get the related Person class would be to build a Fetch Request to query the database and find the Person instances that have the Computer as a member.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSPredicate *predicate = // define your NSPredicate to find the Person object here
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

Generally speaking, that's annoying. So, it's generally a good idea to define your relationships bi-directionally (e.g. with inverse) if possible, that would enable you to just do:

Person *person = computer.person;
0

精彩评论

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