2010-09-16 133 views
0

我是核心數據編程的新手,正在努力研究所涉及的概念。我有一個對象叫做Lease,它與Apartment對象有多對多的關係。給定Lease對象,如何獲得相關對象的Apartment對象或相關對象的NSArray的計數?核心數據 - 相關記錄數

謝謝!

~~加思

回答

6

有幾個不同的方式:

  1. 使用生成的核心數據訪問:

    NSSet * apartments = [myLease apartments]; 
    NSUInteger numberOfApartments = [apartments count];
  2. 使用KeyPaths:

    NSSet * apartments = [myLease valueForKey:@"apartments"]; 
    NSUInteger numberOfApartments = [apartments valueForKey:@"@count"];
  3. 使用KVC(如果你的類是完全KVC兼容):

    NSUInteger numberOfApartments = [myLease countOfApartments];
  4. 使用讀取請求:

    NSFetchRequest * r = [[NSFetchRequest alloc] init]; 
    [r setEntity:apartmentEntityDescription]; 
    [r setPredicate:[NSPredicate predicateWithFormat:@"lease = %@", myLease]]; 
    NSArray * apartments = [myManagedObjectContext executeFetchRequest:r error:nil]; 
    NSUInteger numberOfApartments = [myManagedObjectContext countForFetchRequest:r error:nil]; 
    [r release];

隨意混合和匹配這些線。

+2

怎麼樣通過'apartments。@ count'排序? – 2011-02-15 12:03:19