Search code examples
objective-ccore-dataios5nsfetchrequest

fetchRequestFromTemplateWithName variables


I'm using Xcode 4.2.1 and trying to use a variable. I understand in xcode 4 you need to set the variable with $variable. I have in Xcode for my fetch request the variable as $currDate

fetch request

and my code as

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYYMMdd"];
    NSDate *currDate = [NSDate date];
    NSString *currDateString = [dateFormatter stringFromDate:currDate];
    NSError *error;
    NSFetchRequest *fetchRequest = [[[DataManager sharedInstance] objectModel] fetchRequestFromTemplateWithName:@"fetchAppointmentsByDate" substitutionVariables:[NSDictionary dictionaryWithObject:currDateString forKey:@"currDate"]];
     NSLog(@"Fetch Request: %@", fetchRequest);
    NSArray *appts = [[[DataManager sharedInstance] managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Fetch Request Results: %i %@ - %@", [appts count], appts, error);

However it is not returning ANY results and I know results are there.

Log:

2012-02-24 14:16:29.332 MyApp[2687:fb03] Fetch Request: <NSFetchRequest: 0xb7641c0> (entity: Appointments; predicate: (date == "$currDate"); sortDescriptors: ((null)); type: NSManagedObjectResultType; )
2012-02-24 14:16:29.334 MyApp[2687:fb03] Fetch Request Results: 0 (
) - (null)

However if I change $currDate to 20120224 inside the above screenshot in Xcode it works fine.

Am I doing the variable thing for fetch request templates wrong in xcode 4.2?

UPDATE 1:

So it should look like this? enter image description here


Solution

  • Click on the attribute name which in your case is date and select "Expression" in the popup menu. That allows you to input the variables.

    In your case set the Expression field to: date == $currDate

    That works for me.

    EDIT: To get more like Xcode 3 tree type of situation, you hold down the option key, you can add a sub-predicates in the same way. The '+' sign changes to the "..." when you hold the option key down like so:

    Hold down the option key

    You can achieve the same result that way.