Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...