2012年4月13日金曜日

[iOS]executeFetchRequestを使用した検索方法

    NSString *foo = @"hoge";
    NSString *bar = @"huga";
    
    //Coredate検索
    NSFetchRequest *request = [[NSFetchRequestalloc] init];
    //検索先entityを設定
    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Card"
                                              inManagedObjectContext:managedObjectContext_];
    [request setEntity: entity];
    //検索条件を設定
    NSString *predicateCommand = [NSStringstringWithFormat:@"foo MATCHES '%@' and bar CONTAINS '%@' and isHoge == YES", foo, bar];
    NSPredicate *predicate = [NSPredicatepredicateWithFormat:predicateCommand];
    [request setPredicate: predicate];
    //fetch開始
    NSArray *fetchedObjects = [[selfmanagedObjectContext] executeFetchRequest:request
                                                                         error:nil];
    
    if ([fetchedObjects count]) {
        NSManagedObject *managedObject;
        for (managedObject in fetchedObjects) {
            //managedObjectを削除
            NSString *data = [managedObject valueForKey:@"data"];
        }
        
    } else {
        //No result
    }