CoreDataのクエリーの書き方(NSPredicate,NSSortDescriptor)の書き方

全体の流れ
1.エンティティをセット
2.検索条件をセット(NSPredicate)
3.並び順をセット(NSSortDescriptor)
4.クエリー実行
5.CoreDataのクエリーだけでなく、CloudKitからのクエリーやNSArrayからの検索にも使える
6.NSPredicateは単純な比較もかけるし、predicateWithBlockを使えばかなり複雑なことも書ける

NSEntityDescription*entity = [NSEntityDescription entityForName:@”Item” inManagedObjectContext:self.context];
NSFetchRequest*req = [[NSFetchRequest alloc]init];

//リクエストにエンティティをセット
[req setEntity:entity];

//検索条件をセット
NSPredicate*predicate=[NSPredicate predicateWithFormat:@”registDate = %@”,selectedDate];
[req setPredicate:predicate];

//ソートを書く
NSSortDescriptor*sort1=[[NSSortDescriptor alloc]initWithKey:@”name” ascending:YES];
NSSortDescriptor*sort2=[[NSSortDescriptor alloc]initWithKey:@”registDate” ascending:YES];
NSArray*sortArray=@[sort1,sort2];
[req setSortDescriptors:sortArray];

//実行
NSArray*result=[self.context executeFetchRequest:req error:&error];


 

//中の要素をみながら比較する場合。条件に一致する場合はYESを返す
NSPredicate*predicate=[NSPredicate predicateWithBlock:^BOOL(id  record, NSDictionary * bindings) {
    if([record valueForKey:@”registDate”] == selectedDate){
        return YES;
    }else{
        return NO;
    }
}];