奇怪的NSPredicate行为?

时间:2013-10-04 01:39:21

标签: ios objective-c cocoa-touch core-data

目前,我有一个视频对象填充的表视图,具体取决于录制和保存时使用[nsdate date];拍摄的日期。但是, 可以在一天内录制多个视频。我按日期对它们进行排序,当有多个具有相同日期的视频时,它会显示该日期记录的第一个视频,最新的视频按照最新的顺序按升序排列。我不确定为什么会发生这种情况,但想检查是否有多个视频记录相同的日期,它会按照标题进行组织。在SQL中我可以做类似的事情:

ORDER BY DATE_RECORDED, TITLE ASC

以下是我目前正在做的事情:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = [appDelegate managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"whosVideo == %@", _currentPerson];
[request setPredicate:predicate];
NSEntityDescription *eval = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:_managedObjectContext];
[request setEntity:eval];

NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"date_recorded"
                            ascending:NO
                             selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];


[request setSortDescriptors:sortDescriptors];

NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil){
    //handle error
}

[self setVideoArray:mutableFetchResults];
[self.tableView reloadData];

如果在同一日期记录了多个对象,我将如何处理添加第二个谓词?

1 个答案:

答案 0 :(得分:1)

如果你想处理多个谓词而不是你必须使用NSCompoundPredicate,请尝试如下: -

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"whosVideo == %@", _currentPerson];

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"whosVideo == %@", _someOther];

  NSArray *subPredicates = [[NSArray alloc] initWithObjects:predicate1, predicate2,nil];

NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];