核心数据 - 相关记录的数量

时间:2010-09-16 15:56:25

标签: iphone objective-c core-data

我是Core Data编程的新手,正在尝试解决所涉及的概念。我有一个名为Lease的对象,它与Apartment个对象具有多对多的关系。给定Lease对象,如何获取相关对象的相关Apartment对象或NSArray的计数?

谢谢!

~~加斯

1 个答案:

答案 0 :(得分:6)

有几种不同的方式:

  1. 使用生成的Core Data访问器:

    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];
  5. 随意混合搭配这些线条。