溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Coredata第二課 實體間的關(guān)系

發(fā)布時間:2020-06-27 15:29:16 來源:網(wǎng)絡(luò) 閱讀:294 作者:wcrane 欄目:開發(fā)技術(shù)
問題

如果多個實體之間有關(guān)聯(lián),比如Student擁有多本書(Book),怎么像數(shù)據(jù)庫一樣的能夠表示這種關(guān)系?

解決方法

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

1 .打開Core Data的模型文件,可以看到每個Entity都有一個Relationships可以設(shè)置。我們在Student里面添加一個books屬性,并將它的類型(Type)設(shè)置為To Many(一對多)。 Coredata第二課 實體間的關(guān)系

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

Coredata第二課 實體間的關(guān)系

3 .通過“Editor > NSManagedObject Subclass...”創(chuàng)建兩個實體所對應(yīng)的類。

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)
//沒有實現(xiàn)- (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來表示一對多的關(guān)系的。這里之所以沒有使用數(shù)組是因為需要保證數(shù)據(jù)的唯一性。我們還需要注意的是,在Student類中生成了許多管理Book的方法,但是這些方法都是沒有實現(xiàn)的。比如我們需要添加一個增加Book的功能,就需要實現(xiàn)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];//創(chuàng)建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];//創(chuàng)建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對象的關(guān)系。

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 .從結(jié)果可以看到,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自動替我們管理了實體(對象)之間的依賴關(guān)系,能夠省去不少代碼。

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


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI