繁体   English   中英

使用NSPredicate从核心数据访问对象

[英]Accessing objects using NSPredicate from Core Data

我试图找到我的简单问题的答案,但是没有运气。。。我正在研究CoreData,我有两个实体以“照片和摄影师”一对多的关系为例,这意味着一个摄影师可以拥有多张照片。现在我确实使用

[NSEntityDescription insertNewObjectForEntityForName...]

我在从特定摄影师那里检索“所有照片”时遇到问题。 我正在使用此代码

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Photographer"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name = %@",@"photographerName"];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:YES]];

此代码返回摄影师,但是我只需要该摄影师拍摄的所有照片。 我是CoreData的新手,我不确定是否应该使用“照片”实体?

提前致谢。

您的提取请求应请求Photo实体。

然后,可以在谓词中指定摄影师的姓名,如下所示:

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"photographer.name = %@",@"photographerName"];

或者更好的是,首先获取摄影师对象,然后测试谓词中的关系会更快得多:

Photographer* photographer = ... //Get required photographer here
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"photographer = %@", photographer];

使用它来排序photographer.photos数组。

NSSortDescriptor *sortKey = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:YES];
NSArray *sorters = [NSArray arrayWithObject:sortKey]; 
NSArray *sortedArray = [photographer.photos sortedArrayUsingDescriptors:sorters];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM