如何访问Core Data中的数据

时间:2012-04-26 14:08:44

标签: objective-c ios

我在iOS应用程序中使用Core Data。我有这样的模特: 我的问题是,我如何访问我的数据,例如:如何检索带有“id_page”的书?谢谢你的回答

   #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>

    @class Note, Page;

    @interface Book : NSManagedObject

    @property (nonatomic, retain) NSString * id_book;
    @property (nonatomic, retain) NSSet *page;
    @property (nonatomic, retain) NSSet *note;

    -(Note*)noteForPage;
    -(Page*)pageForPageNumber:(int)pageNumber;

    @end

    @interface Book (CoreDataGeneratedAccessors)

    - (void)addPageObject:(Page *)value;
    - (void)removePageObject:(Page *)value;
    - (void)addPage:(NSSet *)values;
    - (void)removePage:(NSSet *)values;
    - (void)addNoteObject:(Note *)value;
    - (void)removeNoteObject:(Note *)value;
    - (void)addNote:(NSSet *)values;
    - (void)removeNote:(NSSet *)values;
    @end

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Page : NSManagedObject

@property (nonatomic, retain) NSString * id_page;

@end

我创建了一本书和这样的页面:

ook *book = [NSEntityDescription
                  insertNewObjectForEntityForName:@"Book"
                  inManagedObjectContext:context];

    Page *page1 = [NSEntityDescription
                                       insertNewObjectForEntityForName:@"Page"
                                       inManagedObjectContext:context];
    [page1 setValue:@"firstPage" forKey:@"id_page"];

    Page *page2 = [NSEntityDescription
                   insertNewObjectForEntityForName:@"Page"
                   inManagedObjectContext:context];
    [page2 setValue:@"secondPage" forKey:@"id_page"];

    Page *page3 = [NSEntityDescription
                   insertNewObjectForEntityForName:@"Page"
                   inManagedObjectContext:context];
    [page3 setValue:@"ThirdPage" forKey:@"id_page"];

    // create a set of pages
    NSSet *pageSets = [[NSSet alloc]initWithObjects:page1,page2,page3, nil];
    [book addPage:pageSets];

2 个答案:

答案 0 :(得分:0)

使用NSFetchRequest这是一个关于核心数据入门的精彩教程:http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started

答案 1 :(得分:0)

- (Book *)bookWithIdStr:(NSString *)idStr {
  NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Book"];
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id_book MATCHES %@", idStr];
  fetchRequest.predicate = predicate;
  return [[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] lastObject];
}