0

I have a problem with Core Data which has left me at the end of my tether. So I was wondering if any of you wonderful people could help.

Basically, I have two entities in a Core Data project. These are:

Author {authorName, dateOfBirth}
Book {bookName, pages}

There is a one-to-many relationship from author to books called 'authors', and an inverse relationship called 'books'. I have exported the subclasses of these entities, and created my fetch controller. Do I now have to define the relationship programatically?

A list of authors is currently displayed in my table view. At the moment, I can only display a list of ALL the books in my Core Data project when I tap on an author. How would I go about accessing a list of books from a particular author? I am presuming I would use an NSPredicate, the logic I have for that so far is:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY authors.bookName LIKE[cd] %@", authorName];

... but I am pretty sure that is incorrect.

I have been crawling the web for hours for an answer and remain confused. So any help would be greatly appreciated.

Many thanks :)

4

2 回答 2

0

您可能会遇到以下情况:

@interface AuthorListController : UITableViewController {
    UITableView *table;
    NSArray *authors; // array of NSManagedObjects
}

@property (nonatomic, retain) IBOutlet UITableView *table;
@property (nonatomic, retain) NSArray *authors;

在您的实施中,您有:

-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    NSManagedObject *author = [authors objectAtIndex:indexPath.row];
    // create and show your book-level view here
}

现在您已经获得了选定的作者对象,您可以直接获得书籍(假设您已经在 Data Modeler 中设置了一对多关系):

NSSet *books = author.books;

但是,如果您没有加载作者对象,无论出于何种原因,您都可以构建一个新的搜索并在谓词中使用 books->authors 关系:

NSManagedObjectContext *objectContext = self.managedObjectContext;
NSEntityDescription *entity = [NSEntity entityForName:@"Books" inManagedObjectContext:objectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author.name == %@", authorName];
[fetch setPredicate:predicate];

// ... create your error object and execute the fetch, etc
于 2010-08-01T22:59:03.770 回答
0

成员变量“books”存在于您的 Author 类中,并指向 NSManagedObject 记录的 NSSet,所有这些都将是 Book 对象。

显然,您可以获取作者对象,因此在给定作者对象的情况下获取该作者的书籍列表:

NSManagedObject *author = [self getSelectedAuthor];
NSSet *booksByAuthor = [author valueForKey:@"books"];
NSArray *booksArray = [booksByAuthor allObjects]; 

然后,您可以使用 NSArray 来填充 UITableView。

XCode 能够为您的核心数据实体自动创建托管对象类。打开您的 xcdatamodel 文件,选择实体之一,然后选择 File -> New。您应该看到托管对象类作为一个选项。这将允许您创建 Author 和 Book 类作为 NSManagedObject 的子类。这些类将实体的每个属性定义为一个属性,这意味着上面的代码可以读取:

Author *author = [self getSelectedAuthor];
NSSet *booksByAuthor = author.books;
NSArray *booksArray = [booksByAuthor allObjects];
于 2010-08-01T21:15:46.133 回答