我是Core Data编程的新手,正在尝试解决所涉及的概念。我有一个名为Lease
的对象,它与Apartment
个对象具有多对多的关系。给定Lease
对象,如何获取相关对象的相关Apartment
对象或NSArray的计数?
谢谢!
~~加斯
答案 0 :(得分:6)
有几种不同的方式:
使用生成的Core Data访问器:
NSSet * apartments = [myLease apartments]; NSUInteger numberOfApartments = [apartments count];
使用KeyPaths:
NSSet * apartments = [myLease valueForKey:@"apartments"]; NSUInteger numberOfApartments = [apartments valueForKey:@"@count"];
使用KVC(如果您的班级完全符合KVC标准):
NSUInteger numberOfApartments = [myLease countOfApartments];
使用获取请求:
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];
随意混合搭配这些线条。