Coredata第二課 實體間的關係

問題

如果多個實體之間有關聯,比如Student擁有多本書(Book),怎麼像數據庫一樣的能夠表示這種關係?

解決方法

Core Data提供了relationship來表示實體(Entity)之間的這種關係,包括一對一、一對多等。

1 .打開Core Data的模型文件,可以看到每個Entity都有一個Relationships可以設置。我們在Student裏面添加一個books屬性,並將它的類型(Type)設置爲To Many(一對多)。

2 .給Books添加一個owner屬性,並將Inverse設爲books。這樣的話,只要將book對象添加到Studentbooks中,就會自動將owner屬性指向該Student對象。通過改變實體的展示樣式能夠讓我們看的更加清楚。

3 .通過“Editor > NSManagedObject Subclass...”創建兩個實體所對應的類。

Book:

@interface Book : NSManagedObject
@property (nonatomic, retain) NSString * title;
@property (nonatomic) float price;
@property (nonatomic, retain) Student *owner;
@end

Student:

@interface Student : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic) int32_t age;
@property (nonatomic, retain) NSOrderedSet *books;
@end

@interface Student (CoreDataGeneratedAccessors)
//沒有實現- (void)insertObject:(Book *)value inBooksAtIndex:(NSUInteger)idx;
- (void)removeObjectFromBooksAtIndex:(NSUInteger)idx;
- (void)insertBooks:(NSArray *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeBooksAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInBooksAtIndex:(NSUInteger)idx withObject:(Book *)value;
- (void)replaceBooksAtIndexes:(NSIndexSet *)indexes withBooks:(NSArray *)values;
- (void)addBooksObject:(Book *)value;- (void)removeBooksObject:(Book *)value;
- (void)addBooks:(NSOrderedSet *)values;- (void)removeBooks:(NSOrderedSet *)values;
@end

Student是通過一個NSOrderdSet來表示一對多的關係的。這裏之所以沒有使用數組是因爲需要保證數據的唯一性。我們還需要注意的是,在Student類中生成了許多管理Book的方法,但是這些方法都是沒有實現的。比如我們需要添加一個增加Book的功能,就需要實現addBooksObject:

- (void)addBooksObject:(Book *)value {
    NSMutableOrderedSet *books = [self.books mutableCopy];
    [books addObject:value];
    self.books = books;}

4 .保存Student對象與Book對象。

NSManagedObjectContext *context = [AppDelegate appDelegate].managedObjectContext;NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];//創建Student對象Student *stu = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];int r = arc4random_uniform(1000);stu.name = [NSString stringWithFormat:@"Zhangsan: %d", r];NSEntityDescription *bEntity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];//創建Book對象Book *book = [[Book alloc] initWithEntity:bEntity insertIntoManagedObjectContext:context];book.title = @"紅樓夢";//添加Book對象[stu addBooksObject:book];//保存Student對象[context insertObject:stu];[context save:nil];

5 .查詢Student對象,並通過打印查看是否保存了Book,並且能否通過book.owner得到它與Student對象的關係。

NSManagedObjectContext *context = [AppDelegate appDelegate].managedObjectContext;NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];NSArray *arr = [context executeFetchRequest:request error:nil];for (Student *stu in arr) {
    NSLog(@"Name: %@", stu.name);
    for (Book *b in stu.books) {
        NSLog(@"Book: %@ -> %@", b.title, b.owner);
    }}

6 .從結果可以看到,b.owner確實指向了一個Student對象。

2015-02-04 09:07:43.391 02-03-CoreDataRelationship[5169:235934] Name: Zhangsan: 333
2015-02-04 09:07:43.394 02-03-CoreDataRelationship[5169:235934] Book: 紅樓夢 -> <Student: 0x7f9720d48bd0> (entity: Student; id: 0xd000000000040000 <x-coredata://C07E5BAC-C3F6-44B6-B21C-C3D3FBFA4ED1/Student/p1> ; data: {
    age = 0;
    books =     (
        "0xd000000000040002 <x-coredata://C07E5BAC-C3F6-44B6-B21C-C3D3FBFA4ED1/Book/p1>"
    );
    name = "Zhangsan: 333";})

7 .總的來說Core Data自動替我們管理了實體(對象)之間的依賴關係,能夠省去不少代碼。

本文檔由長沙戴維營教育整理。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章