Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS when building nspredicate

I am calculating the number of months between a birthdate and today. With that number, I am building a predicate to fetch objects from core data. Although the number of months is calculated correctly (as the log shows), I am getting a EXC_BAD_ACCESS when building the predicate.

Here is my code:

    NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];

    NSUInteger unitFlags = NSMonthCalendarUnit;

    NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:birthdate
                                              toDate:today options:0];
    int months = [components month];
    NSLog(@"months: %ld", (long)months);
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(alter_min_monat > %@)", months];

Why is this happening?

like image 497
mrd Avatar asked May 12 '14 13:05

mrd


1 Answers

The issue is the placeholder, not with NSPredicate directly, but with initWithFormat: that is innerly called.

%@ shouldn't be used with an int, use %d instead.

So this line:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(alter_min_monat > %@)", months];

Should be:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(alter_min_monat > %d)", months];

Other linked information : String Programming Guide: String Format Specifiers

like image 134
Larme Avatar answered Oct 27 '22 06:10

Larme