开发者

Core-Data: How to set up relationship from one object to specific one in many objects with same name?

I have a question in core data:

there are 2 Entities in the project, Books and Pages; there are 3 Object开发者_如何学运维s books user created in Entity Books; there are several Objects pages user created in Entity Pages; relationship inbetween is one page belongs to one book, one book has many pages.

and my question: there are 3 book with the same object name "book",and each has unique attribute .bookName : @"metal" ;@"plastic" ;@"glass". how to set page to the book with .bookName = @"glass" ?

    //In BookViewController
    Books *book = (Books *)[NSEntityDescription insertNewObjectForEntityForName:@"Books" inManagedObjectContext:managedObjectContext];
    //textView.text is user input text
    book.bookName = textView.text;


    //In PageViewController
    Pages *page = (Pages *)[NSEntityDescription insertNewObjectForEntityForName:@"Pages" inManagedObjectContext:managedObjectContext];
    page.itsbook = WHAT?

Thank you for reading, I stuck here like: a day, really appreciate your help, love you!


If you need to find a specific book then you need to use a NSFetchRequest to ask Core data for it.

Quite some code is needed, so you probably add a convinience method to your Bookclass that looks something like this:

+(Book*)bookWithName:(NSString*)name
{
    // 0. I assume you have something like this to get the context…
    NSManagedObjectContext* context = [NSManagedObjectContext threadLocalContext];

    // 1. Create an empty request
    NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];

    // 2. Set the entity description for the object to fetch
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Book"
                                              inManagedObjectContext:context];
    [request setEntity:entity];

    // 3. Set a predicate asking for objects with a mathing bookName property
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"%K LIKE[cd] %@", 
                                                              @"bookName",
                                                              name];
    [request setPredicate:predicate];

    // 4. Execute the request on the managed object context.
    NSArray* objects = [context executeFetchRequest:request error:NULL];

    // 5. Result is an array, maybe handle empty array and many objects?
    return [objects lastObject];
 }


I'm not sure what you mean. If you want to insert a page as a subset of the book you want this line of code:

[book addPageToBookObject:page]; // the method will be the relationship name

If you want to get the book from the page object you'll need an inverse relationship from the pages to the book.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜